diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 4331226..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/pkg/
-*.pyc
-database/atuned.db
diff --git a/Documentation/plugin/api.txt b/Documentation/plugin/api.txt
deleted file mode 100644
index b99ca2a..0000000
--- a/Documentation/plugin/api.txt
+++ /dev/null
@@ -1,2964 +0,0 @@
-The CPI & MPI api manual
-========================
-
-Help on CPI in module plugin.plugin object:
-
-class CPI(builtins.object)
- | The configurator plugin
- |
- | Methods defined here:
- |
- | __init__(self)
- | Initialize.
- |
- | :param: None
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Class methods defined here:
- |
- | get_configurator(module, submod) from builtins.type
- | Get configurator of 'module'.'submod'.
- |
- | :param module & submod: [('AFFINITY', 'IRQ'), ('AFFINITY', 'TASK'), ('BIOS', 'BIOS'), ('BOOTLOADER', 'GRUB2'), ('KERNEL_CONFIG', 'KERNEL_CONFIG'), ('SCRIPT', 'SCRIPT'), ('SYSCTL', 'SYSCTL'), ('SYSFS', 'SYSFS'), ('SYSTEMCTL', 'SYSTEMCTL'), ('ULIMIT', 'ULIMIT')]
- | :returns cpi: Success, the found configurator
- | :raises LookupError: Fail, find configurator error
- |
- | get_configurators(module=None, submod=None) from builtins.type
- | Get configurators of 'module'.'submod'.
- |
- | :param module(optional): {'SCRIPT', 'ULIMIT', 'SYSFS', 'BOOTLOADER', 'AFFINITY', 'KERNEL_CONFIG', 'BIOS', 'SYSTEMCTL', 'SYSCTL'}
- | :param submod(optional): {'SCRIPT', 'ULIMIT', 'SYSFS', 'IRQ', 'KERNEL_CONFIG', 'GRUB2', 'TASK', 'BIOS', 'SYSTEMCTL', 'SYSCTL'}
- | :returns list: Success, all found configurators or null
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors defined here:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on IrqAffinity in module configurator.affinity.irq object:
-
-class IrqAffinity(configurator.common.Configurator)
- | To change the affinity of irqs
- |
- | Method resolution order:
- | IrqAffinity
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on TaskAffinity in module configurator.affinity.task object:
-
-class TaskAffinity(configurator.common.Configurator)
- | To change the affinity of tasks
- |
- | Method resolution order:
- | TaskAffinity
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Bios in module configurator.bios.bios object:
-
-class Bios(configurator.common.Configurator)
- | To change the bios config
- |
- | Method resolution order:
- | Bios
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Grub2 in module configurator.bootloader.grub2 object:
-
-class Grub2(configurator.common.Configurator)
- | To change the grub2 config
- |
- | Method resolution order:
- | Grub2
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on KernelConfig in module configurator.kernel_config.kconfig object:
-
-class KernelConfig(configurator.common.Configurator)
- | To change the kernel config
- |
- | Method resolution order:
- | KernelConfig
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Script in module configurator.script.script object:
-
-class Script(configurator.common.Configurator)
- | The script extention of CPI
- |
- | Method resolution order:
- | Script
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Sysctl in module configurator.sysctl.sysctl object:
-
-class Sysctl(configurator.common.Configurator)
- | To change the /proc/sys/* config
- |
- | Method resolution order:
- | Sysctl
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Sysfs in module configurator.sysfs.sysfs object:
-
-class Sysfs(configurator.common.Configurator)
- | To change the /sys/* config
- |
- | Method resolution order:
- | Sysfs
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Systemctl in module configurator.systemctl.systemctl object:
-
-class Systemctl(configurator.common.Configurator)
- | To change the system service config
- |
- | Method resolution order:
- | Systemctl
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on Ulimit in module configurator.ulimit.ulimit object:
-
-class Ulimit(configurator.common.Configurator)
- | To change the resources limit of user
- |
- | Method resolution order:
- | Ulimit
- | configurator.common.Configurator
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from configurator.common.Configurator:
- |
- | backup(self, config, rollback_info)
- | Backup from the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :param rollback_info: The additional info for rollback, mostly a path
- | :returns Exceptions: Fail, error in _backup()
- | :returns value: Success, config info
- | :raises: None
- |
- | get(self, key)
- | Get the given config.
- |
- | :param key: The config to be getted, string like "key"
- | :returns None: Success
- | :returns value: Success, config value string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this configurator.
- |
- | :param: None
- | :returns: The module of this configurator
- | :raises: None
- |
- | resume(self, config_info)
- | Resume from the saved config info.
- |
- | :param config_info: The config info to be resumed
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _resume()
- | :returns Exceptions: Fail, error in _resume()
- | :raises: None
- |
- | set(self, config)
- | Set the given config.
- |
- | :param config: The config to be setted, string like "key = value"
- | :returns None: Success
- | :returns NeedRebootWarning: Success, but need reboot
- | :returns SetConfigError: Fail, fail in _set()
- | :returns Exceptions: Fail, error in _set()
- | :raises Exceptions: Error, unexpected errors
- |
- | submod(self)
- | Get the the sub module of this configurator.
- |
- | :param: None
- | :returns: The sub module of this configurator
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from configurator.common.Configurator:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MPI in module plugin.plugin object:
-
-class MPI(builtins.object)
- | The monitor plugin
- |
- | Methods defined here:
- |
- | __init__(self)
- | Initialize.
- |
- | :param: None
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Class methods defined here:
- |
- | get_monitor(module, purpose) from builtins.type
- | Get monitor of 'module' for 'purpose'.
- |
- | :param module & purpose: [('MEM', 'NUMA'), ('MEM', 'TOPO'), ('MEM', 'BANDWIDTH'), ('MEM', 'VMSTAT'), ('MEM', 'UTIL'), ('NET', 'INFO'), ('NET', 'STAT'), ('NET', 'ESTAT'), ('NET', 'TOPO'), ('PERF', 'STAT'), ('PERF', 'TOP'), ('CPU', 'INFO'), ('CPU', 'STAT'), ('CPU', 'TOPO'), ('STORAGE', 'STAT'), ('STORAGE', 'TOPO'), ('SYS', 'BIOS'), ('SYS', 'LDAVG'), ('SYS', 'TASKS'), ('SYS', 'FDUTIL')]
- | :returns mpi: Success, the found monitor
- | :raises LookupError: Fail, find monitor error
- |
- | get_monitors(module=None, purpose=None) from builtins.type
- | Get monitors of 'module' for 'purpose'.
- |
- | :param module(optional): {'NET', 'STORAGE', 'MEM', 'PERF', 'SYS', 'CPU'}
- | :param purpose(optional): {'STAT', 'ESTAT', 'LDAVG', 'TASKS', 'FDUTIL', 'NUMA', 'TOP', 'TOPO', 'UTIL', 'INFO', 'VMSTAT', 'BIOS', 'BANDWIDTH'}
- | :returns list: Success, all found monitors or null
- | :raises: None
- |
- | get_monitors_data(monitors) from builtins.type
- | Get given monitors report data in one.
- |
- | :param monitors: ((module, purpose, options), ...)
- | options is for report(para)
- | :returns list: Success, decoded data strings of all given monitors
- | :returns Exceptions: Success, formatted info
- | :raises LookupError: Fail, find monitor error
- |
- | ----------------------------------------------------------------------
- | Data descriptors defined here:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MemNuma in module monitor.memory.numainfo object:
-
-class MemNuma(monitor.common.Monitor)
- | To collect the memory numa info
- |
- | Method resolution order:
- | MemNuma
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MemTopo in module monitor.memory.topo object:
-
-class MemTopo(monitor.common.Monitor)
- | To collect the memory topo
- |
- | Method resolution order:
- | MemTopo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, json, table]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MemBandwidth in module monitor.memory.bandwidth object:
-
-class MemBandwidth(monitor.common.Monitor)
- | To collect memory bandwidth stat info
- |
- | Method resolution order:
- | MemBandwidth
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=Total/CPU0/CPU1/CPU0_Die0/CPU0_Die1/CPU1_Die0/CPU1_Die1/CPU0_Die0_R/CPU0_Die1_R/CPU1_Die0_R/CPU1_Die1_R/CPU0_Die0_W/CPU0_Die1_W/CPU1_Die0_W/CPU1_Die1_W]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MemVmstat in module monitor.memory.vmstat object:
-
-class MemVmstat(monitor.common.Monitor)
- | To collect the vm stat info
- |
- | Method resolution order:
- | MemVmstat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=procs.r/procs.b/memory.swpd/memory.free/memory.buff/memory.cache/swap.si/swap.so/io.bi/io.bo/system.in/system.cs/cpu.us/cpu.sy/cpu.id/cpu.wa/cpu.st]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on MemUtilStat in module monitor.memory.utilstat object:
-
-class MemUtilStat(monitor.common.Monitor)
- | To collect the mem util stat info
- |
- | Method resolution order:
- | MemUtilStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=time/kbmemfree/kbavail/kbmemused/memused/kbbuffers/kbcached/kbcommit/commit/kbactive/kbinact/kbdirty]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on NetInfo in module monitor.network.info object:
-
-class NetInfo(monitor.common.Monitor)
- | To collect the nic config info
- |
- | Method resolution order:
- | NetInfo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on NetStat in module monitor.network.netstat object:
-
-class NetStat(monitor.common.Monitor)
- | To collect the nic stat info
- |
- | Method resolution order:
- | NetStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--nic=x, --fields=time/nic/rxpcks/txpcks/rxkBs/txkBs/rxcmps/txcmps/rxmcsts/ifutil]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on NetEStat in module monitor.network.netestat object:
-
-class NetEStat(monitor.common.Monitor)
- | To collect the nic estat info
- |
- | Method resolution order:
- | NetEStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--nic=x, --fields=time/nic/rxerrs/txerrs/colls/rxdrops/txdrops/txcarrs/rxframs/rxfifos/txfifos/errs/util]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on NetTopo in module monitor.network.topo object:
-
-class NetTopo(monitor.common.Monitor)
- | To collect the nic topo
- |
- | Method resolution order:
- | NetTopo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, xml, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on PerfStat in module monitor.performance.stat object:
-
-class PerfStat(monitor.common.Monitor)
- | To collect the perf stat info
- |
- | Method resolution order:
- | PerfStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=cycles/instructions/branches/branch-misses/cache-misses/cache-references/dTLB-load-misses/dTLB-loads/iTLB-load-misses/iTLB-loads/stalled-cycles-backend/memstall-load/memstall-store/IPC/BRANCH-MISS-RATIO/CACHE-MISS-RATIO/DTLB-LOAD-MISS-RATIO/ITLB-LOAD-MISS-RATIO/MPKI/SBPI/SBPC/MEMORY-BOUND/STORE-BOUND]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on PerfTop in module monitor.performance.top object:
-
-class PerfTop(monitor.common.Monitor)
- | To collect the perf top snapshot
- |
- | Method resolution order:
- | PerfTop
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=overhead/command/object/symbol]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on CpuInfo in module monitor.processor.info object:
-
-class CpuInfo(monitor.common.Monitor)
- | To collect the CPU info
- |
- | Method resolution order:
- | CpuInfo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, xml, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on CpuStat in module monitor.processor.stat object:
-
-class CpuStat(monitor.common.Monitor)
- | To collect the CPU stat info
- |
- | Method resolution order:
- | CpuStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--cpu=n, --fields=time/cpu/usr/nice/sys/iowait/irq/soft/steal/guest/gnice/idle]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on CpuTopo in module monitor.processor.topo object:
-
-class CpuTopo(monitor.common.Monitor)
- | To collect the CPU topo
- |
- | Method resolution order:
- | CpuTopo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, xml]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on IoStat in module monitor.storage.iostat object:
-
-class IoStat(monitor.common.Monitor)
- | To collect the storage stat info
- |
- | Method resolution order:
- | IoStat
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--device=x, --fields=dev/rs/ws/rMBs/wMBs/rrqms/wrqms/rrqm/wrqm/r_await/w_await/aqu-sz/rareq-sz/wareq-sz/svctm/util]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on StorageTopo in module monitor.storage.topo object:
-
-class StorageTopo(monitor.common.Monitor)
- | To collect the storage topo
- |
- | Method resolution order:
- | StorageTopo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, xml, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on SysBiosInfo in module monitor.system.bios object:
-
-class SysBiosInfo(monitor.common.Monitor)
- | To collect the system BIOS info
- |
- | Method resolution order:
- | SysBiosInfo
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, xml, json]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [%s]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on SysLdavg in module monitor.system.ldavg object:
-
-class SysLdavg(monitor.common.Monitor)
- | To collect the system load average statistics
- |
- | Method resolution order:
- | SysLdavg
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=time/runq-sz/plist-sz/ldavg-1/ldavg-5/ldavg-15/blocked/task-util]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on SysTasks in module monitor.system.tasks object:
-
-class SysTasks(monitor.common.Monitor)
- | To collect the task creation and switching statistics
- |
- | Method resolution order:
- | SysTasks
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=time/procs/cswchs]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
-Help on SysFdUtil in module monitor.system.filed object:
-
-class SysFdUtil(monitor.common.Monitor)
- | To collect the file handles util info
- |
- | Method resolution order:
- | SysFdUtil
- | monitor.common.Monitor
- | builtins.object
- |
- | Methods defined here:
- |
- | __init__(self, user=None)
- | Initialize.
- |
- | :param user(optional): "UT" for unit test, others are ignored
- | :returns: None
- | :raises: None
- |
- | decode(self, info, para)
- | The inner method to decode collected info.
- |
- | :param info: The collected info string
- | :param para: The option for decode,
- | [--fields=fd-util]:
- | "--fields=" to select which data
- | "--cpu=" to select which cpu
- | "--nic=" to select which net interface
- | "--device=" to select which device
- | :returns info: Success, decoded info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | ----------------------------------------------------------------------
- | Methods inherited from monitor.common.Monitor:
- |
- | format(self, info, fmt)
- | The inner method to format collected info.
- |
- | :param info: The decoded info
- | :param fmt: The option for format,
- | [raw, data, %s]:
- | "raw" for original string
- | "xml" for xml string
- | "json" for json string
- | "data" for list of decoded data string
- | "table" for pretty table string
- | :returns info: Success, formatted info
- | :raises NotImplementedError: Error, not supported
- | :raises Exceptions: Fail, with info
- |
- | get(self, para=None)
- | Get the collected info.
- |
- | :param para(optional): The option for get
- | :returns info: Success, collected info string
- | :returns Exceptions: Fail, error in _get()
- | :raises: None
- |
- | module(self)
- | Get the the module of this monitor.
- |
- | :param: None
- | :returns: The module of this monitor
- | :raises: None
- |
- | output(self, info, path)
- | The method to output collected info to file.
- |
- | :param info: The formatted info
- | :param path: The path to output, None for pass through
- | :returns None: Success
- | :returns info: Success, output info
- | :raises: None
- |
- | purpose(self)
- | Get the the purpose of this monitor.
- |
- | :param: None
- | :returns: The purpose of this monitor
- | :raises: None
- |
- | report(self, fmt, path, para=None)
- | Report the given config.
- |
- | :param fmt: The option for format(fmt)
- | :param path: The path to output, None for pass through
- | :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- | :returns None: Success
- | :returns info: Success, output info
- | :returns Exceptions: Fail, with info
- | :raises: None
- |
- | ----------------------------------------------------------------------
- | Data descriptors inherited from monitor.common.Monitor:
- |
- | __dict__
- | dictionary for instance variables (if defined)
- |
- | __weakref__
- | list of weak references to the object (if defined)
-
diff --git a/Documentation/plugin/example.conf b/Documentation/plugin/example.conf
deleted file mode 100644
index 4994853..0000000
--- a/Documentation/plugin/example.conf
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# example of atuned profile configuration
-#
-
-[main]
-# list it's parent profile
-
-
-[tip]
-# the recommended optimization, which should be performed manunaly
-
-
-[check]
-# check the environment
-
-
-[affinity.irq]
-# to change the affinity of irqs
-
-
-[affinity.task]
-# to change the affinity of tasks
-
-
-[bios]
-# to change the bios config
-
-
-[bootloader.grub2]
-# to change the grub2 config
-
-
-[kernel_config]
-# to change the kernel config
-
-
-[script]
-# the script extention of cpi
-
-
-[sysctl]
-# to change the /proc/sys/* config
-
-
-[sysfs]
-# to change the /sys/* config
-
-
-[systemctl]
-# to change the system service config
-
-
-[ulimit]
-# to change the resources limit of user
-
-
diff --git a/License/LICENSE b/License/LICENSE
deleted file mode 100644
index cefc2d2..0000000
--- a/License/LICENSE
+++ /dev/null
@@ -1,121 +0,0 @@
- 木兰宽松许可证, 第1版
-
- 木兰宽松许可证, 第1版
- 2019年8月 http://license.coscl.org.cn/MulanPSL
-
- 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第1版(“本许可证”)的如下条款的约束:
-
- 0. 定义
-
- “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
-
- “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
-
- “法人实体”是指提交贡献的机构及其“关联实体”。
-
- “关联实体”是指,对“本许可证”下的一方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
-
- “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
-
- 1. 授予版权许可
-
- 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
-
- 2. 授予专利许可
-
- 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括仅因您或他人修改“贡献”或其他结合而将必然会侵犯到的专利权利要求。如您或您的“关联实体”直接或间接地(包括通过代理、专利被许可人或受让人),就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
-
- 3. 无商标许可
-
- “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。
-
- 4. 分发限制
-
- 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
-
- 5. 免责声明与责任限制
-
- “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
-
- 条款结束。
-
- 如何将木兰宽松许可证,第1版,应用到您的软件
-
- 如果您希望将木兰宽松许可证,第1版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步:
-
- 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
-
- 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中;
-
- 3, 请将如下声明文本放入每个源文件的头部注释中。
-
- Copyright (c) [2019] [name of copyright holder]
- [Software Name] is licensed under the Mulan PSL v1.
- You can use this software according to the terms and conditions of the Mulan PSL v1.
- You may obtain a copy of Mulan PSL v1 at:
- http://license.coscl.org.cn/MulanPSL
- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- PURPOSE.
- See the Mulan PSL v1 for more details.
-
-
- Mulan Permissive Software License,Version 1
-
- Mulan Permissive Software License,Version 1 (Mulan PSL v1)
- August 2019 http://license.coscl.org.cn/MulanPSL
-
- Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v1 (this License) with following terms and conditions:
-
- 0. Definition
-
- Software means the program and related documents which are comprised of those Contribution and licensed under this License.
-
- Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
-
- Legal Entity means the entity making a Contribution and all its Affiliates.
-
- Affiliates means entities that control, or are controlled by, or are under common control with a party to this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
-
- Contribution means the copyrightable work licensed by a particular Contributor under this License.
-
- 1. Grant of Copyright License
-
- Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
-
- 2. Grant of Patent License
-
- Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed, excluding of any patent claims solely be infringed by your or others’ modification or other combinations. If you or your Affiliates directly or indirectly (including through an agent, patent licensee or assignee), institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
-
- 3. No Trademark License
-
- No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4.
-
- 4. Distribution Restriction
-
- You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
-
- 5. Disclaimer of Warranty and Limitation of Liability
-
- The Software and Contribution in it are provided without warranties of any kind, either express or implied. In no event shall any Contributor or copyright holder be liable to you for any damages, including, but not limited to any direct, or indirect, special or consequential damages arising from your use or inability to use the Software or the Contribution in it, no matter how it’s caused or based on which legal theory, even if advised of the possibility of such damages.
-
- End of the Terms and Conditions
-
- How to apply the Mulan Permissive Software License,Version 1 (Mulan PSL v1) to your software
-
- To apply the Mulan PSL v1 to your work, for easy identification by recipients, you are suggested to complete following three steps:
-
- i. Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
- ii. Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package;
- iii. Attach the statement to the appropriate annotated syntax at the beginning of each source file.
-
- Copyright (c) [2019] [name of copyright holder]
- [Software Name] is licensed under the Mulan PSL v1.
- You can use this software according to the terms and conditions of the Mulan PSL v1.
- You may obtain a copy of Mulan PSL v1 at:
- http://license.coscl.org.cn/MulanPSL
- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- PURPOSE.
-
- See the Mulan PSL v1 for more details.
diff --git a/Makefile b/Makefile
deleted file mode 100755
index b50d1cf..0000000
--- a/Makefile
+++ /dev/null
@@ -1,53 +0,0 @@
-.PHONY: all clean modules
-
-PKGPATH=pkg
-CURDIR=$(shell pwd)
-PREFIX ?= /usr
-LIBEXEC ?= libexec
-BINDIR = $(DESTDIR)$(PREFIX)/bin
-SYSTEMDDIR = $(DESTDIR)$(PREFIX)/lib/systemd/system
-
-all: modules atune-adm atuned db
-
-atune-adm:
- export GOPATH=`cd ../../;pwd` && go build -v -o $(PKGPATH)/atune-adm cmd/atune-adm/*.go
-
-atuned:
- export GOPATH=`cd ../../;pwd` && go build -v -o $(PKGPATH)/atuned cmd/atuned/*.go
-
-modules:
- export GOPATH=`cd ../../;pwd` && cd ${CURDIR}/modules/server/profile/ && go build -buildmode=plugin -o ${CURDIR}/pkg/daemon_profile_server.so *.go
-
-clean:
- rm -rf $(PKGPATH)/*
-
-db:
- sqlite3 database/atuned.db ".read database/init.sql"
-
-install:
- @echo "BEGIN INSTALL A-Tune"
- mkdir -p $(BINDIR)
- mkdir -p $(SYSTEMDDIR)
- mkdir -p $(DESTDIR)/etc/atuned
- mkdir -p $(DESTDIR)$(PREFIX)/lib/atuned/modules
- mkdir -p $(DESTDIR)$(PREFIX)/share/atuned
- mkdir -p $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/scripts
- mkdir -p $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/analysis
- mkdir -p $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/collector
- mkdir -p $(DESTDIR)/var/lib/atuned
- mkdir -p $(DESTDIR)$(PREFIX)/share/bash-completion/completions
- install -m 640 pkg/daemon_profile_server.so $(DESTDIR)$(PREFIX)/lib/atuned/modules
- install -m 750 pkg/atune-adm $(BINDIR)
- install -m 750 pkg/atuned $(BINDIR)
- install -m 640 misc/atuned.service $(SYSTEMDDIR)
- install -m 640 misc/atuned.cnf $(DESTDIR)/etc/atuned/
- install -m 640 database/atuned.db $(DESTDIR)/var/lib/atuned/
- install -m 640 misc/atune-adm $(DESTDIR)$(PREFIX)/share/bash-completion/completions/
- install -m 640 misc/atune.logo $(DESTDIR)$(PREFIX)/share/atuned
- \cp -rf scripts/* $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/scripts/
- chmod -R 750 $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/scripts/
- \cp -rf analysis/* $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/analysis/
- chmod -R 750 $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/analysis/
- \cp -rf collection/* $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/collector/
- chmod -R 750 $(DESTDIR)$(PREFIX)/$(LIBEXEC)/atuned/collector/
- @echo "END INSTALL A-Tune"
diff --git a/README.md b/README.md
deleted file mode 100644
index e591657..0000000
--- a/README.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# A-Tune介绍
-
-A-Tune是一款系统自优化的系统基础软件,该软件能够自动识别系统的负载类型,实现业务模型到资源模型的动态调度,充分发挥鲲鹏服务器的计算能力。
-
-## 编译环境准备
-
-第一步:**下载Go发行版**
-
-下载链接:https://golang.org/
-
-第二步:**现有目标环境清理**
-
-这步,如果原有环境已经安装过go版本,要先卸载,卸载方法如下:
-
-卸载就是清理
-
-[root@localhost atune]# whereis go
-
-[root@localhost atune]# whereis golang
-
-[root@localhost atune]# whereis gocode #如果需要的话
-
-//找到后删除
-
-rm -rf xxx
-
-第三步:**安装Go发行版**
-tar -C /usr/local -xzf go-xxxxxxxxx.tar.gz
-
-解压后在目录 /usr/local/go中
-
-第四步:**设置Go环境**
-
-设置GOPATH 目录
-
-mkdir -p /home/gocode
-
-编辑环境
-vim /etc/profile
-在最后一行加入 安i插入
-
-export GOROOT=/usr/local/go #设置为go安装的路径
-
-export GOPATH=/home/gocode #默认安装包的路径
-
-export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
-
-执行下面生效配置
-source /etc/profile
-
-验证是否生效
-go version
-输出 go version go1.11 linux/amd64
-
-
-第五步:**解决protoc和protoc-gen-go三方包依赖**
-
-1、下载protobuf源码:https://github.com/golang/protobuf
-
-2、执行make install
-
-3、把生成的protoc和proto-gen-go的二进制所在路径设置到系统PATH上:export PATH=$PATH:/XX/
-
-第六步:**编译atune源码**
-
-执行make all即可
-
diff --git a/analysis/__init__.py b/analysis/__init__.py
deleted file mode 100644
index 864b1cf..0000000
--- a/analysis/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(__file__))
diff --git a/analysis/app.py b/analysis/app.py
deleted file mode 100644
index 1f95573..0000000
--- a/analysis/app.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Application initialization, including log configuration, restful api registration.
-"""
-
-from flask import Flask
-from flask_restful import Api
-import os
-import sys
-from resources import configurator
-from resources import monitor
-from resources import optimizer
-from resources import collector
-from resources import classification
-from resources import profile
-from resources import train
-
-from configparser import ConfigParser
-import logging
-from logging.handlers import RotatingFileHandler, SysLogHandler
-log = logging.getLogger('werkzeug')
-log.setLevel(logging.ERROR)
-
-
-app = Flask(__name__)
-api = Api(app)
-
-api.add_resource(configurator.Configurator, '/v1/setting' ,'/setting')
-api.add_resource(monitor.Monitor, '/v1/monitor' ,'/monitor')
-api.add_resource(optimizer.Optimizer, '/v1/optimizer' ,'/v1/optimizer/')
-api.add_resource(collector.Collector, '/v1/collector','/v1/collector')
-api.add_resource(classification.Classification, '/v1/classification','/v1/classification')
-api.add_resource(profile.Profile, '/v1/profile','/v1/profile')
-api.add_resource(train.Training, '/v1/training','/v1/training')
-
-
-def configLog(level):
- loggingFormat = logging.Formatter('atuned: %(asctime)s [%(levelname)s] %(name)s : %(message)s')
- syslogHandler = SysLogHandler(address="/dev/log", facility=SysLogHandler.LOG_LOCAL0)
- syslogHandler.setFormatter(loggingFormat)
- syslogHandler.setLevel(level)
-
- rootLogger = logging.getLogger()
- rootLogger.addHandler(syslogHandler)
-
-
-def main(filename):
- if not os.path.exists(filename):
- print("conf file is not exist")
- return
- config = ConfigParser()
- config.read(filename)
-
- level = logging.getLevelName(config.get("log", "level").upper())
- configLog(level)
- app.run(host="localhost", port=config.get("server", "rest_port"))
-
-
-if __name__ == '__main__':
- if len(sys.argv) != 2:
- print("lack of conf file parameter")
- sys.exit(-1)
- main(sys.argv[1])
diff --git a/analysis/models/cpu_clf.m b/analysis/models/cpu_clf.m
deleted file mode 100644
index d77ae76..0000000
Binary files a/analysis/models/cpu_clf.m and /dev/null differ
diff --git a/analysis/models/cpu_clu.m b/analysis/models/cpu_clu.m
deleted file mode 100644
index 769dc7b..0000000
Binary files a/analysis/models/cpu_clu.m and /dev/null differ
diff --git a/analysis/models/cpu_scaler.pkl b/analysis/models/cpu_scaler.pkl
deleted file mode 100644
index 8f6dbe7..0000000
Binary files a/analysis/models/cpu_scaler.pkl and /dev/null differ
diff --git a/analysis/models/cpuio_clf.m b/analysis/models/cpuio_clf.m
deleted file mode 100644
index 024ac55..0000000
Binary files a/analysis/models/cpuio_clf.m and /dev/null differ
diff --git a/analysis/models/cpuio_scaler.pkl b/analysis/models/cpuio_scaler.pkl
deleted file mode 100644
index 9e9625a..0000000
Binary files a/analysis/models/cpuio_scaler.pkl and /dev/null differ
diff --git a/analysis/models/cpuiomem_clf.m b/analysis/models/cpuiomem_clf.m
deleted file mode 100644
index 7df119b..0000000
Binary files a/analysis/models/cpuiomem_clf.m and /dev/null differ
diff --git a/analysis/models/cpuiomem_scaler.pkl b/analysis/models/cpuiomem_scaler.pkl
deleted file mode 100644
index fdcbf21..0000000
Binary files a/analysis/models/cpuiomem_scaler.pkl and /dev/null differ
diff --git a/analysis/models/cpumem_clf.m b/analysis/models/cpumem_clf.m
deleted file mode 100644
index 6e79f79..0000000
Binary files a/analysis/models/cpumem_clf.m and /dev/null differ
diff --git a/analysis/models/cpumem_scaler.pkl b/analysis/models/cpumem_scaler.pkl
deleted file mode 100644
index 58c07af..0000000
Binary files a/analysis/models/cpumem_scaler.pkl and /dev/null differ
diff --git a/analysis/models/cpunet_clf.m b/analysis/models/cpunet_clf.m
deleted file mode 100644
index c86bc87..0000000
Binary files a/analysis/models/cpunet_clf.m and /dev/null differ
diff --git a/analysis/models/cpunet_scaler.pkl b/analysis/models/cpunet_scaler.pkl
deleted file mode 100644
index 8e9a596..0000000
Binary files a/analysis/models/cpunet_scaler.pkl and /dev/null differ
diff --git a/analysis/models/cpunetmem_clf.m b/analysis/models/cpunetmem_clf.m
deleted file mode 100644
index f08313a..0000000
Binary files a/analysis/models/cpunetmem_clf.m and /dev/null differ
diff --git a/analysis/models/cpunetmem_scaler.pkl b/analysis/models/cpunetmem_scaler.pkl
deleted file mode 100644
index 63fbda6..0000000
Binary files a/analysis/models/cpunetmem_scaler.pkl and /dev/null differ
diff --git a/analysis/models/custom_clf.h5 b/analysis/models/custom_clf.h5
deleted file mode 100644
index 7e18aed..0000000
Binary files a/analysis/models/custom_clf.h5 and /dev/null differ
diff --git a/analysis/models/encoder.pkl b/analysis/models/encoder.pkl
deleted file mode 100644
index 8351537..0000000
Binary files a/analysis/models/encoder.pkl and /dev/null differ
diff --git a/analysis/models/io_clf.m b/analysis/models/io_clf.m
deleted file mode 100644
index 16a88a9..0000000
Binary files a/analysis/models/io_clf.m and /dev/null differ
diff --git a/analysis/models/io_clu.m b/analysis/models/io_clu.m
deleted file mode 100644
index 9aa4828..0000000
Binary files a/analysis/models/io_clu.m and /dev/null differ
diff --git a/analysis/models/io_scaler.pkl b/analysis/models/io_scaler.pkl
deleted file mode 100644
index d387685..0000000
Binary files a/analysis/models/io_scaler.pkl and /dev/null differ
diff --git a/analysis/models/mem_clu.m b/analysis/models/mem_clu.m
deleted file mode 100644
index 6a8b5c1..0000000
Binary files a/analysis/models/mem_clu.m and /dev/null differ
diff --git a/analysis/models/net_clf.m b/analysis/models/net_clf.m
deleted file mode 100644
index d81641d..0000000
Binary files a/analysis/models/net_clf.m and /dev/null differ
diff --git a/analysis/models/net_clu.m b/analysis/models/net_clu.m
deleted file mode 100644
index 8bdbe00..0000000
Binary files a/analysis/models/net_clu.m and /dev/null differ
diff --git a/analysis/models/net_scaler.pkl b/analysis/models/net_scaler.pkl
deleted file mode 100644
index ce54d63..0000000
Binary files a/analysis/models/net_scaler.pkl and /dev/null differ
diff --git a/analysis/models/non_clf.m b/analysis/models/non_clf.m
deleted file mode 100644
index 262fff3..0000000
Binary files a/analysis/models/non_clf.m and /dev/null differ
diff --git a/analysis/models/non_scaler.pkl b/analysis/models/non_scaler.pkl
deleted file mode 100644
index dd1f199..0000000
Binary files a/analysis/models/non_scaler.pkl and /dev/null differ
diff --git a/analysis/models/scaler.pkl b/analysis/models/scaler.pkl
deleted file mode 100644
index 661e483..0000000
Binary files a/analysis/models/scaler.pkl and /dev/null differ
diff --git a/analysis/optimizer/__init__.py b/analysis/optimizer/__init__.py
deleted file mode 100644
index 23457e6..0000000
--- a/analysis/optimizer/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
diff --git a/analysis/optimizer/optimizer.py b/analysis/optimizer/optimizer.py
deleted file mode 100644
index 1a65d89..0000000
--- a/analysis/optimizer/optimizer.py
+++ /dev/null
@@ -1,93 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-This class is used to find optimal settings and generate optimized profile.
-"""
-
-import numpy as np
-from multiprocessing import Process
-from skopt.optimizer import gp_minimize
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class Optimizer(Process):
- def __init__(self, name, params, child_conn, engine = "bayes", max_eval=50):
- super(Optimizer, self).__init__(name=name)
- self.knobs = params
- self.child_conn = child_conn
- self.engine = engine
- self.max_eval = int(max_eval)
-
- def build_space(self):
- objective_params_list = []
- for p in self.knobs:
- if p['type'] == 'discrete':
- if p['dtype'] == 'int':
- items = p['items']
- r = p['range']
- s = 1
- if 'step' in p.keys():
- s = p['step']
- if r is not None:
- for i in range(0, len(r), 2):
- items.extend(list(np.arange(r[i], r[i + 1], step=s)))
- objective_params_list.append(items)
- if p['dtype'] == 'string':
- items = p['options']
- keys = []
- for i in range(len(items)):
- keys.append(i)
- objective_params_list.append(keys)
- elif p['type'] == 'continuous':
- r = p['range']
- objective_params_list.append((r[0], r[1]))
- return objective_params_list
-
- def run(self):
- def objective(var):
- for i, knob in enumerate(self.knobs):
- params[knob['name']] = var[i]
- print(params)
- self.child_conn.send(params)
- result = self.child_conn.recv()
- x = 0.0
- evalList = result.split(',')
- for value in evalList:
- num = float(value)
- x = x + num
- return x
-
- ref = []
- params = {}
- for knob in self.knobs:
- ref.append(int(knob['ref']))
- try:
- logger.info("Running performance evaluation.......")
- ret = gp_minimize(objective, self.build_space(), n_calls=self.max_eval)
- logger.info("Minimization procedure has been completed.")
- except ValueError as v:
- logger.error('Value Error:', v)
-
- for i, knob in enumerate(self.knobs):
- params[knob['name']] = ret.x[i]
- self.child_conn.send(params)
- logger.info("Optimized result: %s" % (params))
- logger.info("The optimized profile has been generated.")
- return params
-
- def stopProcess(self):
- self.child_conn.close()
- self.terminate()
diff --git a/analysis/optimizer/workload_characterization.py b/analysis/optimizer/workload_characterization.py
deleted file mode 100644
index 1822b1b..0000000
--- a/analysis/optimizer/workload_characterization.py
+++ /dev/null
@@ -1,400 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-This class is used to train models and characterize system workload.
-"""
-
-import os
-import glob
-import hashlib
-import numpy as np
-import pandas as pd
-from sklearn import svm
-from collections import Counter
-from xgboost import XGBClassifier
-from sklearn.cluster import KMeans
-from sklearn.externals import joblib
-from sklearn.metrics import accuracy_score
-from sklearn.ensemble import AdaBoostClassifier
-from sklearn.model_selection import train_test_split as tts
-from sklearn.preprocessing import StandardScaler, LabelEncoder
-
-class WorkloadCharacterization(object):
- def __init__(self, model_path):
- self.model_path = model_path
- self.scaler = StandardScaler()
- self.encoder = LabelEncoder()
- self.dataset = None
- self.X = None
- self.y = None
-
- def parsing(self, data_path):
- df = [ ]
- print (data_path)
- csvfiles = glob.glob(data_path)
- for csv in csvfiles:
- print ("file:", csv)
- data = pd.read_csv(csv, index_col=None, header=None)
- df.append(data)
- dataset = pd.concat(df)
- self.dataset = dataset
- return dataset
-
- def clustering(self, data_path):
- complete_path = os.path.join(data_path,"*.csv")
- self.parsing(complete_path)
- dataset = self.dataset.drop([28,41,42,43,44,57,58], axis=1)
- cpu_util = pd.concat([dataset.iloc[:,8], dataset.iloc[:,45]], axis=1, join='inner')
- io_util = pd.concat([dataset.iloc[:,3], dataset.iloc[:,19]], axis=1, join='inner')
- net_util = dataset.iloc[:,25]
- mem_total = dataset.iloc[:,29]
-
- cpu_path = os.path.join(self.model_path,'cpu_clu.m')
- io_path = os.path.join(self.model_path,'io_clu.m')
- net_path = os.path.join(self.model_path,'net_clu.m')
- mem_path = os.path.join(self.model_path,'mem_clu.m')
-
- cpu = KMeans(n_clusters=2)
- s = cpu.fit(cpu_util)
- joblib.dump(cpu, cpu_path)
- c_pred = cpu.predict(cpu_util)
-
- io = KMeans(n_clusters=2)
- s = io.fit(io_util)
- joblib.dump(io, io_path)
- i_pred = io.predict(io_util)
-
- net = KMeans(n_clusters=2)
- x= [[x] for x in net_util]
- s = net.fit(x)
- joblib.dump(net, net_path)
- n_pred = net.predict(x)
-
- mem = KMeans(n_clusters=2)
- x= [[x] for x in mem_total]
- s = mem.fit(x)
- joblib.dump(mem, mem_path)
- m_pred = mem.predict(x)
-
- result = pd.concat([pd.DataFrame(c_pred), pd.DataFrame(i_pred), pd.DataFrame(n_pred), pd.DataFrame(m_pred)], axis=1)
- cpu_result = result.iloc[:,0].map(lambda x:str(x))
- io_result = result.iloc[:,1].map(lambda x:str(x))
- net_result = result.iloc[:,2].map(lambda x:str(x))
- mem_result = result.iloc[:,3].map(lambda x:str(x))
- label = cpu_result.str.cat(io_result)
- label = label.str.cat(net_result)
- label = label.str.cat(mem_result)
- dataset.insert(0, 'label', label)
- dataset.to_csv('clusteringresult.csv')
-
- def labelling(self, data):
- cpu_path = os.path.join(self.model_path,'cpu_clu.m')
- io_path = os.path.join(self.model_path,'io_clu.m')
- net_path = os.path.join(self.model_path,'net_clu.m')
- mem_path = os.path.join(self.model_path,'mem_clu.m')
-
- cpu = joblib.load(cpu_path)
- io = joblib.load(io_path)
- net = joblib.load(net_path)
- mem = joblib.load(mem_path)
-
- X = pd.DataFrame(data)
-
- cpu_util = pd.concat([X.iloc[:,8], X.iloc[:,45]], axis=1, join='inner')
- io_util = pd.concat([X.iloc[:,3], X.iloc[:,19]], axis=1, join='inner')
- net_util = [[x] for x in X.iloc[:, 25]]
- mem_total = [[x] for x in X.iloc[:, 29]]
-
- ctype = cpu.predict(cpu_util)
- itype = io.predict(io_util)
- ntype = net.predict(net_util)
- mtype = mem.predict(mem_total)
- cpred = Counter(ctype).most_common(1)[0]
- ipred = Counter(itype).most_common(1)[0]
- npred = Counter(ntype).most_common(1)[0]
- mpred = Counter(mtype).most_common(1)[0]
-
- print ("The clustering result is", cpred[0], ipred[0], npred[0], mpred[0])
- print ("The accuracy of the label prediction are ", cpred[1]/len(data),
- ipred[1]/len(data), npred[1]/len(data), mpred[1]/len(data))
- return [cpred[0], ipred[0], npred[0], mpred[0]]
-
- def svm_clf(self, clfpath, kernel):
- X_train, X_test, y_train, y_test = tts(self.X, self.y, test_size=0.3)
-
- rbf = svm.SVC(kernel= kernel, C=200)
- rbf.fit(X_train, y_train)
- rbf_score = rbf.score(X_test, y_test)
- print ("the accuracy of rbf classification is %f" %rbf_score)
- joblib.dump(rbf, clfpath)
-
- def ada_clf(self, clfpath):
- X_train, X_test, y_train, y_test = tts(self.X, self.y, test_size=0.3)
- adaboost = AdaBoostClassifier(n_estimators=1000, learning_rate=0.05)
- adaboost.fit(X_train, y_train)
- adaboost_score = adaboost.score(X_test, y_test)
- print ("the accuracy of adaboost is %f" %adaboost_score)
- print ("the feature importances of this classifier are", adaboost.feature_importances_)
- joblib.dump(adaboost, clfpath)
-
- def xgb_clf(self, clfpath):
- X_train, X_test, y_train, y_test = tts(self.X, self.y, test_size=0.3)
- model = XGBClassifier(learning_rate=0.1, n_estimators=400, max_depth=6, min_child_weight = 0.5, gamma=0.01,
- subsample=1, colsample_btree=1, scale_pos_weight=1, random_state=27, slient = 0, alpha=100)
- model.fit(X_train,y_train)
- y_pred = model.predict(X_test)
- print ("the accuracy of xgboost is %f" %accuracy_score(y_test,y_pred))
- print ("the feature importances of this classifier are", model.feature_importances_)
- joblib.dump(model, clfpath)
-
- def train(self, data_path):
- encoder_path = os.path.join(self.model_path,"encoder.pkl")
- complete_path = os.path.join(data_path,"*.csv")
-
- io_path = os.path.join(data_path,"*0100.csv")
- net_path = os.path.join(data_path,"*0010.csv")
- cpu_path = os.path.join(data_path,"*1000.csv")
- cpumem_path = os.path.join(data_path,"*1001.csv")
- cpuio_path = os.path.join(data_path,"*1100.csv")
- cpunet_path = os.path.join(data_path,"*1010.csv")
- cpuiomem_path = os.path.join(data_path,"*1101.csv")
- cpunetmem_path = os.path.join(data_path,"*1011.csv")
-
- io_clf = os.path.join(self.model_path,"io_clf.m")
- net_clf = os.path.join(self.model_path,"net_clf.m")
- cpu_clf = os.path.join(self.model_path,"cpu_clf.m")
- cpumem_clf = os.path.join(self.model_path,"cpumem_clf.m")
- cpuio_clf = os.path.join(self.model_path,"cpuio_clf.m")
- cpuiomem_clf = os.path.join(self.model_path,"cpuiomem_clf.m")
- cpunet_clf = os.path.join(self.model_path,"cpunet_clf.m")
- cpunetmem_clf = os.path.join(self.model_path,"cpunetmem_clf.m")
-
- io_scl = os.path.join(self.model_path,"io_scaler.pkl")
- net_scl = os.path.join(self.model_path,"net_scaler.pkl")
- cpu_scl = os.path.join(self.model_path,"cpu_scaler.pkl")
- cpumem_scl = os.path.join(self.model_path,"cpumem_scaler.pkl")
- cpuio_scl = os.path.join(self.model_path,"cpuio_scaler.pkl")
- cpuiomem_scl = os.path.join(self.model_path,"cpuiomem_scaler.pkl")
- cpunet_scl = os.path.join(self.model_path,"cpunet_scaler.pkl")
- cpunetmem_scl = os.path.join(self.model_path,"cpunetmem_scaler.pkl")
-
- self.parsing(complete_path)
- self.y = self.encoder.fit_transform(self.dataset.iloc[:, -1])
- joblib.dump(self.encoder, encoder_path)
-
- self.parsing(io_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, io_scl)
- self.svm_clf(io_clf, 'sigmoid')
- print ("The classifier for io-intensive workload has been generated.")
-
- self.parsing(net_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, net_scl)
- self.svm_clf(net_clf, 'sigmoid')
- print ("The classifier for net-intensive workload has been generated.")
-
- self.parsing(cpu_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpu_scl)
- self.xgb_clf(cpu_clf)
- print ("The classifier for cpu-intensive workload has been generated.")
-
- self.parsing(cpumem_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpumem_scl)
- self.svm_clf(cpumem_clf, 'rbf')
- print ("The classifier for cpumem-intensive workload has been generated.")
-
- self.parsing(cpuio_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpuio_scl)
- self.svm_clf(cpuio_clf, 'rbf')
- print ("The classifier for cpuio-intensive workload has been generated.")
-
- self.parsing(cpunet_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpunet_scl)
- self.svm_clf(cpunet_clf, 'rbf')
- print ("The classifier for cpunet-intensive workload has been generated.")
-
- self.parsing(cpuiomem_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpuiomem_scl)
- self.svm_clf(cpuiomem_clf, 'rbf')
- print ("The classifier for cpuiomem-intensive workload has been generated.")
-
- self.parsing(cpunetmem_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:,:-1])
- self.y = self.encoder.transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, cpunetmem_scl)
- self.svm_clf(cpunetmem_clf, 'rbf')
- print ("The classifier for cpunetmem-intensive workload has been generated.")
-
- def identify(self, x):
- x = pd.DataFrame(x)
- x = x.drop([28,41,42,43,44,57,58], axis=1)
- l = self.labelling(x)
-
- encoder_path = os.path.join(self.model_path,'encoder.pkl')
-
- io_scaler = os.path.join(self.model_path,'io_scaler.pkl')
- net_scaler = os.path.join(self.model_path,'net_scaler.pkl')
- cpu_scaler = os.path.join(self.model_path,'cpu_scaler.pkl')
- cpuio_scaler = os.path.join(self.model_path,'cpuio_scaler.pkl')
- cpuiomem_scaler = os.path.join(self.model_path,'cpuiomem_scaler.pkl')
- cpunet_scaler = os.path.join(self.model_path,'cpunet_scaler.pkl')
- cpumem_scaler = os.path.join(self.model_path,'cpumem_scaler.pkl')
- cpunetmem_scaler = os.path.join(self.model_path,'cpunetmem_scaler.pkl')
-
- io_clf = os.path.join(self.model_path,'io_clf.m')
- net_clf = os.path.join(self.model_path,'net_clf.m')
- cpu_clf = os.path.join(self.model_path,'cpu_clf.m')
- cpumem_clf = os.path.join(self.model_path,'cpumem_clf.m')
- cpuio_clf = os.path.join(self.model_path,'cpuio_clf.m')
- cpunet_clf = os.path.join(self.model_path,'cpunet_clf.m')
- cpuiomem_clf = os.path.join(self.model_path,'cpuiomem_clf.m')
- cpunetmem_clf = os.path.join(self.model_path,'cpunetmem_clf.m')
-
- if l == [0, 0, 0, 0]:
- resourcelimit = " "
- print ("The workload has been identified as non-intensive type")
- return resourcelimit, "default", 1
- elif l == [0, 0, 0, 1] :
- resourcelimit = "io"
- print ("The workload has been identified as mem-intensive type")
- return resourcelimit, "in-memory_computing", 1
- elif l == [0, 0, 1, 0] :
- resourcelimit = "network"
- scaler = joblib.load(net_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as network-intensive type")
- model = joblib.load(net_clf)
- result = model.predict(x)
- elif l == [0, 1, 0, 0] :
- resourcelimit = "io"
- scaler = joblib.load(io_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as io-intensive type")
- model = joblib.load(io_clf)
- result = model.predict(x)
- elif l == [1, 0, 0, 0]:
- resourcelimit = "cpu"
- scaler = joblib.load(cpu_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-intensive type")
- model = joblib.load(cpu_clf)
- result = model.predict(x)
- elif l == [1, 0, 0, 1] :
- resourcelimit = "cpu,memory"
- scaler = joblib.load(cpumem_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-mem-intensive type")
- model = joblib.load(cpumem_clf)
- result = model.predict(x)
- elif l == [1, 0, 1, 0] :
- resourcelimit = "cpu,io"
- scaler = joblib.load(cpunet_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-net-intensive type")
- model = joblib.load(cpunet_clf)
- result = model.predict(x)
- elif l == [1, 0, 1, 1] :
- resourcelimit = "cpu,network,memory"
- scaler = joblib.load(cpunetmem_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-net-mem-intensive type")
- model = joblib.load(cpunetmem_clf)
- result = model.predict(x)
- elif l == [1, 1, 0, 0]:
- resourcelimit = "cpu,io"
- scaler = joblib.load(cpuio_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-io-intensive type")
- model = joblib.load(cpuio_clf)
- result = model.predict(x)
- elif l == [1, 1, 0, 1] :
- resourcelimit = "cpu,io,memory"
- scaler = joblib.load(cpuiomem_scaler)
- x = scaler.transform(x)
- print ("The workload has been identified as cpu-io-mem-intensive type")
- model = joblib.load(cpuiomem_clf)
- result = model.predict(x)
- elif l ==[1, 1, 1, 1]:
- resourcelimit = "cpu,io,network,memory"
- print ("The workload has been identified as cpu-io-net-mem-intensive type")
- return resourcelimit, "big_database", 1
- else:
- resourcelimit = ""
- print ("Error: Unsupported classifier type")
- return resourcelimit, "default", 0
-
- encoder = joblib.load(encoder_path)
- result = encoder.inverse_transform(result)
- print (result)
- prediction = Counter(result).most_common(1)[0]
- confidence = prediction[1]/len(result)
- if confidence > 0.5:
- return resourcelimit, prediction[0], confidence
- else:
- return resourcelimit, "default", confidence
-
- def retrain(self, data_path, custom_path):
- custom_path = os.path.abspath(custom_path)
- (dirname, filename) = os.path.split(custom_path)
- (modelname, extension) = os.path.splitext(filename)
- scalername = modelname + '_scaler.pkl'
- encodername = modelname + '_encoder.pkl'
-
- data_path = os.path.join(data_path,"*.csv")
- self.parsing(data_path)
- self.X = self.scaler.fit_transform(self.dataset.iloc[:, :-1])
- self.y = self.encoder.fit_transform(self.dataset.iloc[:, -1])
- joblib.dump(self.scaler, os.path.join(dirname, scalername))
- joblib.dump(self.encoder, os.path.join(dirname, encodername))
-
- class_num = len(self.encoder.classes_)
- if class_num == 1:
- self.y[-1] = self.y[-1] + 1
- self.svm_clf(custom_path)
-
- def reidentify(self, x, custom_path):
- custom_path = os.path.abspath(custom_path)
- (dirname, filename) = os.path.split(custom_path)
- (modelname, extension) = os.path.splitext(filename)
- scalername = modelname + '_scaler.pkl'
- encodername = modelname + '_encoder.pkl'
-
- scaler = joblib.load(os.path.join(dirname, scalername))
- encoder = joblib.load(os.path.join(dirname, encodername))
- model = joblib.load(custom_path)
-
- x = scaler.transform(x)
- result = model.predict(x)
- result = encoder.inverse_transform(result)
- print (result)
-
- prediction = Counter(result).most_common(1)[0]
- confidence = prediction[1]/len(result)
- if confidence > 0.5:
- return prediction[0], confidence
- else:
- return "default", confidence
\ No newline at end of file
diff --git a/analysis/plugin/__init__.py b/analysis/plugin/__init__.py
deleted file mode 100644
index 864b1cf..0000000
--- a/analysis/plugin/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(__file__))
diff --git a/analysis/plugin/configurator/__init__.py b/analysis/plugin/configurator/__init__.py
deleted file mode 100755
index 9f5df04..0000000
--- a/analysis/plugin/configurator/__init__.py
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = [
- "affinity",
- "bios",
- "bootloader",
- "kernel_config",
- "script",
- "sysctl",
- "sysfs",
- "systemctl",
- "ulimit",
- "common"]
-
-from . import *
diff --git a/analysis/plugin/configurator/affinity/__init__.py b/analysis/plugin/configurator/affinity/__init__.py
deleted file mode 100755
index 96a4534..0000000
--- a/analysis/plugin/configurator/affinity/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["irq", "task"]
-
-from . import *
diff --git a/analysis/plugin/configurator/affinity/irq.py b/analysis/plugin/configurator/affinity/irq.py
deleted file mode 100755
index 0d6c7e5..0000000
--- a/analysis/plugin/configurator/affinity/irq.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the affinity of irqs.
-"""
-
-import sys
-import logging
-import os
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class IrqAffinity(Configurator):
- """To change the affinity of irqs"""
- _module = "AFFINITY"
- _submod = "IRQ"
- _option = "/proc/irq"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- self._set.__func__.__doc__ = Configurator._set.__doc__ % (
- 'irq or irq_name', 'cpumask in hex, no "0x" prefix, "," is permitted')
-
- def __get_irq_id(self, key):
- if key.isdecimal():
- id = key
- name = None
- else:
- id = None
- name = key
-
- if id is None:
- irqs = sorted(os.listdir("/sys/kernel/irq/"), key=lambda x: int(x))
- for irq in irqs:
- with open("/sys/kernel/irq/{}/actions".format(irq), 'r') as f:
- action = f.read().replace("\n", "")
- if action == name:
- id = irq
- break
- return id
-
- def _get(self, key):
- id = self.__get_irq_id(key)
- if id is None:
- err = LookupError("Fail to find irq {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- f = open("{opt}/{id}/smp_affinity".format(opt=self._option,
- id=id),
- mode='r',
- buffering=-1,
- encoding=None,
- errors=None,
- newline=None,
- closefd=True)
- ret = f.read().replace(",", "")
- f.close()
- return ret
-
- def _set(self, key, value):
- id = self.__get_irq_id(key)
- if id is None:
- err = LookupError("Fail to find irq {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- mask = value.replace(",", "")
- f = open("{opt}/{id}/smp_affinity".format(opt=self._option,
- id=id),
- mode='w',
- buffering=-1,
- encoding=None,
- errors=None,
- newline=None,
- closefd=True)
- f.write(mask)
- f.close()
- return 0
-
- def _check(self, config1, config2):
- config1 = config1.replace(",", "")
- config2 = config2.replace(",", "")
- return int(config1, base=16) == int(config2, base=16)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = IrqAffinity("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/affinity/task.py b/analysis/plugin/configurator/affinity/task.py
deleted file mode 100755
index 0893dc9..0000000
--- a/analysis/plugin/configurator/affinity/task.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the affinity of tasks.
-"""
-
-import sys
-import logging
-import subprocess
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class TaskAffinity(Configurator):
- """To change the affinity of tasks"""
- _module = "AFFINITY"
- _submod = "TASK"
- _option = "taskset -p"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- self._set.__func__.__doc__ = Configurator._set.__doc__ % (
- 'pid or task_name', 'cpumask in hex, no "0x" prefix, "," is permitted')
-
- def __get_task_id(self, key):
- if key.isdecimal():
- id = key
- name = None
- else:
- id = None
- name = key.replace("(", "\(")
- name = name.replace(")", "\)")
-
- if id is None:
- output = subprocess.check_output("ps -e".split(),
- stderr=subprocess.STDOUT)
- pattern = "^\ *(\d.*?)\ +(.*?)\ +(.*?)\ +" + name
- searchObj = re.search(
- pattern,
- output.decode(),
- re.ASCII | re.MULTILINE)
- if searchObj is not None:
- id = searchObj.group(1)
- return id
-
- def _get(self, key):
- id = self.__get_task_id(key)
- if id is None:
- err = LookupError("Fail to find task {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- output = subprocess.check_output(
- "{opt} {pid}".format(
- opt=self._option,
- pid=id).split(),
- stderr=subprocess.STDOUT)
- pattern = "^pid.*?current affinity mask:\ (.+)"
- searchObj = re.search(
- pattern,
- output.decode(),
- re.ASCII | re.MULTILINE)
- if searchObj is None:
- err = GetConfigError("Fail to find {} affinity".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return searchObj.group(1)
-
- def _set(self, key, value):
- id = self.__get_task_id(key)
- if id is None:
- err = LookupError("Fail to find task {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- mask = value.replace(",", "")
- return subprocess.call(
- "{opt} {mask} {pid}".format(
- opt=self._option,
- mask=mask,
- pid=id).split(),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL)
-
- def _check(self, config1, config2):
- config1 = config1.replace(",", "")
- config2 = config2.replace(",", "")
- return int(config1, base=16) == int(config2, base=16)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = TaskAffinity("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/bios/__init__.py b/analysis/plugin/configurator/bios/__init__.py
deleted file mode 100755
index f522a12..0000000
--- a/analysis/plugin/configurator/bios/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["bios"]
-
-from . import *
diff --git a/analysis/plugin/configurator/bios/bios.py b/analysis/plugin/configurator/bios/bios.py
deleted file mode 100755
index 07008df..0000000
--- a/analysis/plugin/configurator/bios/bios.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the bios config.
-"""
-
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Bios(Configurator):
- """To change the bios config"""
- _module = "BIOS"
- _submod = "BIOS"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
-
- def _set(self, key, value):
- raise NeedConfigWarning(
- "Please change the BIOS configuration {key} to {val}.".format(
- key=key, val=value))
-
- def _get(self, key):
- if key.lower() == "version":
- output = subprocess.check_output(
- "dmidecode -t bios | grep -Po '(?<=Version:)(.*)' | sed 's/^ *//g' | sed 's/ *$//g'",
- shell=True)
- return output.decode()
- elif key.lower() == "hpre_support":
- ret = subprocess.call(
- "lspci | grep HPRE",
- shell=True,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL)
- if ret == 0:
- return "yes"
- else:
- return "no"
- else:
- err = NotImplementedError(
- "{} can not get {}".format(
- self._module, key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def _backup(self, key, rollback_info):
- return ""
-
- def _resume(self, key, value):
- return None
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = Bios("UT")
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/bootloader/__init__.py b/analysis/plugin/configurator/bootloader/__init__.py
deleted file mode 100755
index 65e8a94..0000000
--- a/analysis/plugin/configurator/bootloader/__init__.py
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-import sys
-import os
-sys.path.insert(0, os.path.dirname(__file__))
-__all__ = ["grub2", "cmdline"]
-
-from . import *
diff --git a/analysis/plugin/configurator/bootloader/bootutils.py b/analysis/plugin/configurator/bootloader/bootutils.py
deleted file mode 100644
index b353637..0000000
--- a/analysis/plugin/configurator/bootloader/bootutils.py
+++ /dev/null
@@ -1,43 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Utils class.
-"""
-
-
-class Utils:
- """Utils class"""
-
- @staticmethod
- def get_keypos(str, key):
- keys = [" " + key + "=", " " + key + " ", " " + key + "\n"]
- ret = []
- for k in keys:
- pos = str.rfind(k)
- if pos != -1:
- pos += 1
- ret.append(pos)
- return max(ret)
-
- @staticmethod
- def get_value(key):
- with open("/proc/cmdline", 'r') as f:
- active_cmd = f.read()
- keypos = Utils.get_keypos(active_cmd, key)
- active = None
- if keypos != -1:
- config = active_cmd[keypos:].split()[0]
- if config.find("=") != -1:
- active = config.split("=")[1]
- return active
diff --git a/analysis/plugin/configurator/bootloader/cmdline.py b/analysis/plugin/configurator/bootloader/cmdline.py
deleted file mode 100644
index 0a72f80..0000000
--- a/analysis/plugin/configurator/bootloader/cmdline.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to collect the cmdline info.
-"""
-import sys
-from configurator.common import *
-from bootutils import Utils
-
-
-class Cmdline(Configurator):
- """To collect the cmdline info"""
- _module = "BOOTLOADER"
- _submod = "CMDLINE"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
-
- def _get(self, key):
- return Utils.get_value(key)
-
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key[=value]')
- sys.exit(-1)
- ct = Cmdline("UT1")
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/bootloader/grub2.json b/analysis/plugin/configurator/bootloader/grub2.json
deleted file mode 100755
index 5d3ae75..0000000
--- a/analysis/plugin/configurator/bootloader/grub2.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "hugepagesz": [
- "64k",
- "64K",
- "2m",
- "2M",
- "32m",
- "32M",
- "1g",
- "1G"
- ]
-}
\ No newline at end of file
diff --git a/analysis/plugin/configurator/bootloader/grub2.py b/analysis/plugin/configurator/bootloader/grub2.py
deleted file mode 100755
index 077d232..0000000
--- a/analysis/plugin/configurator/bootloader/grub2.py
+++ /dev/null
@@ -1,145 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the grub2 config.
-"""
-
-import sys
-import logging
-import os
-import subprocess
-import random
-import shutil
-import re
-from bootutils import Utils
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Grub2(Configurator):
- """To change the grub2 config"""
- _module = "BOOTLOADER"
- _submod = "GRUB2"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- __cfg_files = ["/etc/grub2.cfg", "/etc/grub2-efi.cfg"]
- for f in __cfg_files:
- if os.path.isfile(f):
- self.__cfg_file = f
- break
- self.__kernel_ver = subprocess.check_output("uname -r".split()).decode(
- ).replace("\n", "")
-
- def __get_cfg_entry(self, version):
- with open(self.__cfg_file, 'r') as f:
- ctx = f.read()
- pattern = re.compile(
- "\n(menuentry)[^\{\}]*?\{[^\{\}]*?\n\s+(linux)[^\{\}]*?" +
- version.replace(
- ".",
- "\.") +
- "[^\{\}]*?(\})",
- re.ASCII | re.DOTALL)
- searchObj = pattern.search(ctx)
- start = searchObj.span(1)
- cmd = searchObj.span(2)
- end = searchObj.span(3)
- return {"START": start[0], "CMD": cmd[0], "END": end[1]}
-
- def _get(self, key):
- entry = self.__get_cfg_entry(self.__kernel_ver)
- with open(self.__cfg_file, 'r') as f:
- f.seek(entry["CMD"])
- cmd = f.readline()
-
- keypos = Utils.get_keypos(cmd, key)
- if keypos == -1:
- err = GetConfigError("Fail to find {} config".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- config = cmd[keypos:].split()[0]
- if config.find("=") != -1:
- return config.split("=")[1]
- else:
- return None
-
- @pre_check(
- Configurator._precheck,
- os.path.split(
- os.path.realpath(__file__))[0] +
- "/grub2.json")
- def _set(self, key, value):
- entry = self.__get_cfg_entry(self.__kernel_ver)
- if value is None:
- new = key
- else:
- new = "{key}={val}".format(key=key, val=value)
-
- with open(self.__cfg_file, 'r+') as f:
- f.seek(entry["CMD"])
- cmd = f.readline()
-
- keypos = Utils.get_keypos(cmd, key)
- if keypos != -1:
- old = cmd[keypos:].split("\n")[0].split()[0]
- file_modify(f, entry["CMD"] + keypos,
- entry["CMD"] + keypos + len(old) - 1, new)
- else:
- file_modify(f, entry["CMD"] + len(cmd) - 1, -1, " " + new)
-
- active = Utils.get_value(key)
- if value == active:
- return 0
- raise NeedRebootWarning(
- "Need reboot to make the config change of grub2 effect.")
-
- def _backup(self, key, rollback_info):
- name = os.path.basename(self.__cfg_file)
- bak_file = "{path}/{file}{ver}".format(path=rollback_info, file=name,
- ver=random.random())
- shutil.copy(self.__cfg_file, bak_file)
- return "CPI_ROLLBACK_INFO = {}".format(bak_file)
-
- def _resume(self, key, value):
- if key != "CPI_ROLLBACK_INFO":
- err = ValueError("unsupported resume type: {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- shutil.copy(value, self.__cfg_file)
- return None
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key[=value]')
- sys.exit(-1)
- ct = Grub2("UT1")
- save = ct.backup(sys.argv[1], "./1/")
- print(save)
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
- print(ct.resume(save))
diff --git a/analysis/plugin/configurator/common.py b/analysis/plugin/configurator/common.py
deleted file mode 100755
index 7aa3b78..0000000
--- a/analysis/plugin/configurator/common.py
+++ /dev/null
@@ -1,380 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The base class of the configuration, used to set the value, get the value of the given key,
-backup from the given config and resume from the saved config info.
-"""
-
-import sys
-import logging
-import json
-from public import *
-from functools import wraps
-
-logger = logging.getLogger(__name__)
-
-
-class Configurator():
- """Base class for configurators"""
-
- # sub class should init these
- _module = "UNKNOWN"
- _submod = "UNKNOWN"
-
- # for inner options usage
- _option = ""
-
- def __init__(self, user=None):
- """
- Initialize.
-
- :param user(optional): "UT" for unit test, others are ignored
- :returns: None
- :raises: None
- """
- self._user = user
-
- def module(self):
- """
- Get the the module of this configurator.
-
- :param: None
- :returns: The module of this configurator
- :raises: None
- """
- return self._module
-
- def submod(self):
- """
- Get the the sub module of this configurator.
-
- :param: None
- :returns: The sub module of this configurator
- :raises: None
- """
- return self._submod
-
- def _getopt(self):
- """
- Get the the inner option of this configurator.
- Multi-options should be splited by ";".
-
- :param: None
- :returns: The iterator for get all inner options
- :raises: None
- """
- return iter(self._option.split(";"))
-
- def set(self, config):
- """
- Set the given config.
-
- :param config: The config to be setted, string like "key = value"
- :returns None: Success
- :returns NeedRebootWarning: Success, but need reboot
- :returns SetConfigError: Fail, fail in _set()
- :returns Exceptions: Fail, error in _set()
- :raises Exceptions: Error, unexpected errors
- """
- cfg = self._getcfg(config)
- try:
- ret = self._set(cfg[0], cfg[1])
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
-
- if (0 == ret) and self._check(cfg[1], self.get(cfg[0])):
- err = None
- elif cfg[1] is None:
- err = SetConfigError(
- "Fail to set {mod}.{sub} config: {key}".format(
- mod=self.module(), sub=self.submod(), key=cfg[0]))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- else:
- err = SetConfigError("Fail to set {mod}.{sub} config: {key}={val}".format(
- mod=self.module(), sub=self.submod(), key=cfg[0], val=cfg[1]))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
-
- def _precheck(self, key, value, file):
- """
- The common method to precheck config.
-
- :param key: The config key
- :param value: The config value
- :param file: The check file
- :returns None: Success
- :raises TypeError: Fail, invalid rule
- :raises ValueError: Fail, invalid value
- :raises KeyError: Fail, invalid key
- :raises Exceptions: Fail, with info
- """
- with open(file, 'r') as f:
- ctx = f.read()
- check_rules = json.loads(ctx)
-
- if (type(check_rules).__name__ != 'dict'):
- raise TypeError("Invalid rule file")
-
- rule = check_rules.get(key)
- if (type(rule).__name__ == 'NoneType'):
- raise KeyError('Invalid key "{}"'.format(key))
- elif (type(rule).__name__ == 'list'):
- if value in rule:
- return None
- elif (type(rule).__name__ == 'dict'):
- start = rule.get("start")
- end = rule.get("end")
- step = rule.get("step")
- try:
- ranges = list(range(start, end, step))
- except BaseException:
- raise TypeError("Invalid rule")
- if int(value) in ranges:
- return None
- else:
- raise TypeError(
- "Invalid rule type: {}".format(
- type(rule).__name__))
- raise ValueError('Invalid value "{}" for key "{}"'.format(value, key))
-
- def _set(self, key, value):
- """
- The inner method to set config.
- The sub class should implement this method.
-
- :param key: The config key,
- [%s]
- :param value: The config value,
- [%s]
- :returns 0: Success
- :returns errno: Fail
- :raises Exceptions: Fail, with info
- """
- err = NotImplementedError("_set method is not implemented")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def get(self, key):
- """
- Get the given config.
-
- :param key: The config to be getted, string like "key"
- :returns None: Success
- :returns value: Success, config value string
- :returns Exceptions: Fail, error in _get()
- :raises: None
- """
- try:
- ret = self._get(key)
- if ret is not None:
- ret = ret.replace('\n', ' ').strip()
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
- return ret
-
- def _get(self, key):
- """
- The inner method to get config.
- The sub class should implement this method.
-
- :param key: The config key
- :returns None: Success
- :returns value: Success, config value string
- :raises Exceptions: Fail, with info
- """
- err = NotImplementedError("_get method is not implemented")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def _getcfg(self, para):
- """
- Get the the key and value from the config string.
-
- :param para: The config string
- :returns list: Success, e.g. ["key", "value" or None]
- :raises Exceptions: Error, unexpected errors
- """
- cfg = para.split("=", 1)
- for i in range(0, len(cfg)):
- cfg[i] = cfg[i].strip()
- if len(cfg) == 1:
- cfg.append(None)
- return cfg
-
- def _check(self, config1, config2):
- """
- Check whether the given configs are the same.
-
- :param config1: The 1st config value string
- :param config2: The 2nd config value string
- :returns True: Same
- :returns False: Different
- :raises: None
- """
- return config1 == config2
-
- def _backup(self, key, rollback_info):
- """
- The inner method to backup config.
- The sub class should implement this method if needed.
-
- :param key: The config key
- :param rollback_info: The additional info for rollback, mostly a path
- :returns value: Success, config info
- :raises Exceptions: Fail, with info
- """
- val = self._get(key).replace('\n', ' ').strip()
- return "{} = {}".format(key, val)
-
- def backup(self, config, rollback_info):
- """
- Backup from the given config.
-
- :param config: The config to be setted, string like "key = value"
- :param rollback_info: The additional info for rollback, mostly a path
- :returns Exceptions: Fail, error in _backup()
- :returns value: Success, config info
- :raises: None
- """
- cfg = self._getcfg(config)
- try:
- ret = self._backup(cfg[0], rollback_info)
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
- return ret
-
- def _resume(self, key, value):
- """
- The inner method to resume config.
- The sub class should implement this method if needed.
-
- :param key: The config key
- :param value: The config value
- :returns None: Success
- :returns Exceptions: Fail, error in _set()
- :raises Exceptions: Fail, with info
- """
- if key == "CPI_ROLLBACK_INFO":
- err = NotImplementedError("_resume method is not implemented")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return self.set("{} = {}".format(key, value))
-
- def resume(self, config_info):
- """
- Resume from the saved config info.
-
- :param config_info: The config info to be resumed
- :returns None: Success
- :returns NeedRebootWarning: Success, but need reboot
- :returns SetConfigError: Fail, fail in _resume()
- :returns Exceptions: Fail, error in _resume()
- :raises: None
- """
- cfg = self._getcfg(config_info)
- try:
- ret = self._resume(cfg[0], cfg[1])
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
- return ret
-
-
-def file_modify(file, start, end, str):
- file.seek(0)
- content = file.read()
- if end < start:
- content = content[:start] + str + content[start:]
- else:
- content = content[:start] + str + content[end + 1:]
- file.seek(0)
- file.truncate()
- file.write(content)
-
-
-def pre_check(checker=None, file=None, strict=False):
- def wrapper(set):
- @wraps(set)
- def prechecked_set(self, key, value):
- if checker is not None:
- try:
- if file is not None:
- checker(self, key, value, file)
- else:
- checker(self, key, value)
- except TypeError as err:
- if strict is True:
- raise err
- except KeyError as err:
- if strict is True:
- raise err
- except ValueError as err:
- raise err
- except Exception as err:
- if strict is True:
- raise err
- return set(self, key, value)
- return prechecked_set
- return wrapper
diff --git a/analysis/plugin/configurator/kernel_config/__init__.py b/analysis/plugin/configurator/kernel_config/__init__.py
deleted file mode 100755
index df51d94..0000000
--- a/analysis/plugin/configurator/kernel_config/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["kconfig"]
-
-from . import *
diff --git a/analysis/plugin/configurator/kernel_config/kconfig.py b/analysis/plugin/configurator/kernel_config/kconfig.py
deleted file mode 100755
index 977d545..0000000
--- a/analysis/plugin/configurator/kernel_config/kconfig.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the kernel config.
-"""
-
-import sys
-import logging
-import subprocess
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class KernelConfig(Configurator):
- """To change the kernel config"""
- _module = "KERNEL_CONFIG"
- _submod = "KERNEL_CONFIG"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- cfg_file = "/proc/config.gz"
- if os.path.isfile(cfg_file):
- self.__cfg_file = cfg_file
- else:
- self.__kernel_ver = subprocess.check_output(
- "uname -r".split()).decode().replace("\n", "")
- self.__cfg_file = "/boot/config-" + self.__kernel_ver
-
- def _set(self, key, value):
- if self.get(key) == value:
- return 0
- else:
- raise NeedConfigWarning(
- "Please change the kernel configuration {key} to {val}.".format(
- key=key, val=value))
-
- def _get(self, key):
- file_type = os.path.splitext(self.__cfg_file)[-1]
- if file_type == ".gz":
- with gzip.open(self.__cfg_file, 'rt') as f:
- cfgs = f.read()
- else:
- with open(self.__cfg_file, 'r') as f:
- cfgs = f.read()
-
- pattern = re.compile("^" + key + "=(.+)", re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(cfgs)
- if len(searchObj) > 1:
- err = LookupError("find more than one " + key)
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return searchObj[0]
-
- def _backup(self, key, rollback_info):
- return ""
-
- def _resume(self, key, value):
- return None
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = KernelConfig("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/script/__init__.py b/analysis/plugin/configurator/script/__init__.py
deleted file mode 100755
index d67110e..0000000
--- a/analysis/plugin/configurator/script/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["script"]
-
-from . import *
diff --git a/analysis/plugin/configurator/script/script.py b/analysis/plugin/configurator/script/script.py
deleted file mode 100755
index 616115c..0000000
--- a/analysis/plugin/configurator/script/script.py
+++ /dev/null
@@ -1,135 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to extend script for CPI.
-"""
-
-import sys
-import logging
-import os
-import subprocess
-import random
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Script(Configurator):
- """The script extention of CPI"""
- _module = "SCRIPT"
- _submod = "SCRIPT"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
-
- def _set(self, key, value):
- name = os.path.basename(key)
- script = "{}/set.sh".format(key)
- output = subprocess.run(
- "bash {script} {val}".format(
- script=script,
- val=value).split(),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- check=True)
- if len(output.stderr) != 0:
- err = UserWarning(name + ": " + output.stderr.decode())
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return 0
-
- def _get(self, key):
- name = os.path.basename(key)
- script = "{}/get.sh".format(key)
- output = subprocess.run(
- "bash {script}".format(
- script=script).split(),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=True)
- if len(output.stderr) != 0:
- err = UserWarning(name + ": " + output.stderr.decode())
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return output.stdout.decode()
-
- def _check(self, config1, config2):
- return True
-
- def _backup(self, key, rollback_info):
- name = os.path.basename(key)
- script = "{}/backup.sh".format(key)
- if os.path.isfile(script):
- output = subprocess.run(
- "bash {script} {rb_info} {ver}".format(
- script=script,
- rb_info=rollback_info,
- ver=random.random()).split(),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=True)
- if len(output.stderr) != 0:
- err = UserWarning(name + ": " + output.stderr.decode())
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return output.stdout.decode()
- else:
- return Configurator._backup(self, key, rollback_info)
-
- def _resume(self, key, value):
- name = os.path.basename(key)
- script = "{}/resume.sh".format(key)
- if os.path.isfile(script):
- output = subprocess.run(
- "bash {script} {val}".format(
- script=script,
- val=value).split(),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.PIPE,
- check=True)
- if len(output.stderr) != 0:
- err = UserWarning(name + ": " + output.stderr.decode())
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return 0
- else:
- return Configurator._resume(self, key, value)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' script_file=value')
- sys.exit(-1)
- ct = Script("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/sysctl/__init__.py b/analysis/plugin/configurator/sysctl/__init__.py
deleted file mode 100755
index 7f82381..0000000
--- a/analysis/plugin/configurator/sysctl/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["sysctl"]
-
-from . import *
diff --git a/analysis/plugin/configurator/sysctl/sysctl.py b/analysis/plugin/configurator/sysctl/sysctl.py
deleted file mode 100755
index 2ecf05e..0000000
--- a/analysis/plugin/configurator/sysctl/sysctl.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the /proc/sys/* config.
-"""
-
-import sys
-import logging
-import subprocess
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Sysctl(Configurator):
- """To change the /proc/sys/* config"""
- _module = "SYSCTL"
- _submod = "SYSCTL"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- self.__cmd = "sysctl"
-
- def _get(self, key):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} -n {key}".format(
- cmd=self.__cmd, key=key).split(),
- stderr=no_print)
- return output.decode()
-
- def _set(self, key, value):
- with open('/dev/null', 'w') as no_print:
- return subprocess.call('{cmd} -w {key}="{val}"'.format(
- cmd=self.__cmd, key=key, val=value), shell=True,
- stdout=no_print, stderr=no_print)
-
- def _check(self, config1, config2):
- config1 = re.sub("\s{1,}", " ", config1)
- config2 = re.sub("\s{1,}", " ", config2)
- return config1 == config2
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = Sysctl("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/sysfs/__init__.py b/analysis/plugin/configurator/sysfs/__init__.py
deleted file mode 100755
index 5fa51b8..0000000
--- a/analysis/plugin/configurator/sysfs/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["sysfs"]
-
-from . import *
diff --git a/analysis/plugin/configurator/sysfs/sysfs.py b/analysis/plugin/configurator/sysfs/sysfs.py
deleted file mode 100755
index 5e96d53..0000000
--- a/analysis/plugin/configurator/sysfs/sysfs.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the /sys/* config.
-"""
-
-import sys
-import logging
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Sysfs(Configurator):
- """To change the /sys/* config"""
- _module = "SYSFS"
- _submod = "SYSFS"
- _option = "/sys"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
-
- def _get(self, key):
- f = open("{opt}/{key}".format(opt=self._option, key=key), mode='r',
- buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
- ret = f.read()
- f.close()
-
- pattern = ".*\[(.*)\].*"
- searchObj = re.search(pattern, ret, re.ASCII | re.MULTILINE)
- if searchObj is not None:
- return searchObj.group(1)
- else:
- return ret
-
- def _set(self, key, value):
- f = open("{opt}/{key}".format(opt=self._option, key=key), mode='w',
- buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
- f.write(value)
- f.close()
- return 0
-
- def _check(self, config1, config2):
- return True
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = Sysfs("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/systemctl/__init__.py b/analysis/plugin/configurator/systemctl/__init__.py
deleted file mode 100755
index ff3e799..0000000
--- a/analysis/plugin/configurator/systemctl/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["systemctl"]
-
-from . import *
diff --git a/analysis/plugin/configurator/systemctl/systemctl.py b/analysis/plugin/configurator/systemctl/systemctl.py
deleted file mode 100755
index 57a1a47..0000000
--- a/analysis/plugin/configurator/systemctl/systemctl.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the system service config.
-"""
-import os
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Systemctl(Configurator):
- """To change the system service config"""
- _module = "SYSTEMCTL"
- _submod = "SYSTEMCTL"
- _option = "is-active"
- _path = "/usr/lib/systemd/system/"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- self.__cmd = "systemctl"
-
- def _get(self, service):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output(
- "{cmd} {opt} {service}; exit 0".format(
- cmd=self.__cmd,
- opt=self._option,
- service=service),
- stderr=no_print,
- shell=True)
- return output.decode().replace('\n', ' ').strip()
-
- def _set(self, service, oper):
- if not os.path.exists(self._path + service + ".service"):
- return 0
- status = self._get(service)
- if status == "active" and oper == "start" or status == "inactive" and oper == "stop":
- return 0
- with open('/dev/null', 'w') as no_print:
- return subprocess.call("{cmd} {oper} {service}".format(
- cmd=self.__cmd, service=service, oper=oper).split(),
- stdout=no_print, stderr=no_print)
-
- def _check(self, config1, config2):
- return True
-
- def _backup(self, key, rollback_info):
- val = self._get(key)
- if val == "active" or val == "activating":
- val = "start"
- else:
- val = "stop"
- return "{} = {}".format(key, val)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' service=oper')
- sys.exit(-1)
- ct = Systemctl("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/configurator/ulimit/__init__.py b/analysis/plugin/configurator/ulimit/__init__.py
deleted file mode 100755
index d9b25c4..0000000
--- a/analysis/plugin/configurator/ulimit/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["ulimit"]
-
-from . import *
diff --git a/analysis/plugin/configurator/ulimit/ulimit.py b/analysis/plugin/configurator/ulimit/ulimit.py
deleted file mode 100755
index 0fa1700..0000000
--- a/analysis/plugin/configurator/ulimit/ulimit.py
+++ /dev/null
@@ -1,121 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the Configurator, used to change the resources limit of user.
-"""
-
-import sys
-import logging
-import os
-import re
-import random
-import shutil
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from configurator.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class Ulimit(Configurator):
- """To change the resources limit of user"""
- _module = "ULIMIT"
- _submod = "ULIMIT"
-
- def __init__(self, user=None):
- Configurator.__init__(self, user)
- self.__cfg_file = "/etc/security/limits.conf"
-
- def _set(self, key, value):
- f = open(
- self.__cfg_file,
- mode='r+',
- buffering=-1,
- encoding=None,
- errors=None,
- newline=None,
- closefd=True)
- info = f.read()
- keyword = key.split(".")
- pattern = re.compile(
- "^\s*?(?!#)" +
- keyword[0] +
- "\s+?" +
- keyword[1] +
- "\s+?" +
- keyword[2] +
- "\s+(\w+)\s*?",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.search(info)
- if searchObj is not None:
- offset = searchObj.span(1)
- file_modify(f, offset[0], offset[1] - 1, value)
- else:
- file_modify(f, len(info), -1, "\n{domain}\t{type}\t{item}\t{value}".format(
- domain=keyword[0], type=keyword[1], item=keyword[2], value=value))
- f.close()
- return 0
-
- def _get(self, key):
- with open(self.__cfg_file, 'r') as f:
- info = f.read()
- keyword = key.split(".")
- pattern = re.compile(
- "^\s*?(?!#)" +
- keyword[0] +
- "\s+?" +
- keyword[1] +
- "\s+?" +
- keyword[2] +
- "\s+(\w+)\s*?",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = GetConfigError("Fail to find {} config".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- return searchObj[-1]
-
- def _backup(self, key, rollback_info):
- name = os.path.basename(self.__cfg_file)
- bak_file = "{path}/{file}{ver}".format(path=rollback_info, file=name,
- ver=random.random())
- shutil.copy(self.__cfg_file, bak_file)
- return "CPI_ROLLBACK_INFO = {}".format(bak_file)
-
- def _resume(self, key, value):
- if key != "CPI_ROLLBACK_INFO":
- err = ValueError("unsupported resume type: {}".format(key))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- shutil.copy(value, self.__cfg_file)
- return None
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 2:
- print('usage: ' + sys.argv[0] + ' key=value')
- sys.exit(-1)
- ct = Ulimit("UT")
- print(ct.set(sys.argv[1]))
- print(ct.get(ct._getcfg(sys.argv[1])[0]))
diff --git a/analysis/plugin/monitor/__init__.py b/analysis/plugin/monitor/__init__.py
deleted file mode 100755
index 9a88a0a..0000000
--- a/analysis/plugin/monitor/__init__.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = [
- "memory",
- "network",
- "performance",
- "processor",
- "storage",
- "common",
- "system"]
-
-from . import *
diff --git a/analysis/plugin/monitor/common.py b/analysis/plugin/monitor/common.py
deleted file mode 100755
index 05cdd04..0000000
--- a/analysis/plugin/monitor/common.py
+++ /dev/null
@@ -1,266 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The base class of the monitor, used to report the given config, get the collected info,
-decode the collected info, format the collected info and output collected info to file.
-"""
-
-import sys
-import logging
-from public import *
-
-logger = logging.getLogger(__name__)
-
-
-class Monitor():
- """Base class for monitors"""
-
- # sub class should init these
- _module = "UNKNOWN"
- _purpose = "UNKNOWN"
-
- # for inner options usage
- _option = ""
-
- def __init__(self, user=None):
- """
- Initialize.
-
- :param user(optional): "UT" for unit test, others are ignored
- :returns: None
- :raises: None
- """
- self._user = user
-
- def module(self):
- """
- Get the the module of this monitor.
-
- :param: None
- :returns: The module of this monitor
- :raises: None
- """
- return self._module
-
- def purpose(self):
- """
- Get the the purpose of this monitor.
-
- :param: None
- :returns: The purpose of this monitor
- :raises: None
- """
- return self._purpose
-
- def _getopt(self):
- """
- Get the the inner option of this monitor.
- Multi-options should be splited by ";".
-
- :param: None
- :returns: The iterator for get all inner options
- :raises: None
- """
- return iter(self._option.split(";"))
-
- def _getpara(self, paras):
- """
- Get all the configs from one string.
-
- :param paras: The configs string splited by ";"
- :returns None: No parameter
- :returns parameter: next parameter
- :raises: None
- """
- if paras is None:
- return None
-
- try:
- nextp = next(paras)
- except StopIteration:
- return None
-
- if nextp == "":
- nextp = None
- return nextp
-
- def report(self, fmt, path, para=None):
- """
- Report the given config.
-
- :param fmt: The option for format(fmt)
- :param path: The path to output, None for pass through
- :param para: Multi-options for get(para) and decode(para), should be splited by ";"
- :returns None: Success
- :returns info: Success, output info
- :returns Exceptions: Fail, with info
- :raises: None
- """
- try:
- if para is None:
- paras = None
- else:
- paras = iter(para.split(";"))
- info = self._get(self._getpara(paras))
- decoded_info = self.decode(info, self._getpara(paras))
- fmted_info = self.format(decoded_info, fmt)
- return self.output(fmted_info, path)
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
-
- def _get(self, para):
- """
- The inner method to get collected info.
- The sub class should implement this method.
-
- :param para: The option for get,
- [%s]:
- "--interval=" to specify period of time
- "--cpu=" to select which cpu
- "--event=" to select which event
- :returns value: Success, collected info string
- :raises Exceptions: Fail, with info
- """
- err = NotImplementedError("_get method is not implemented")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def get(self, para=None):
- """
- Get the collected info.
-
- :param para(optional): The option for get
- :returns info: Success, collected info string
- :returns Exceptions: Fail, error in _get()
- :raises: None
- """
- try:
- ret = self._get(para)
- except Exception as err:
- if self._user == "UT":
- raise err
- else:
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- return err
- return ret
-
- def decode(self, info, para):
- """
- The inner method to decode collected info.
-
- :param info: The collected info string
- :param para: The option for decode,
- [%s]:
- "--fields=" to select which data
- "--cpu=" to select which cpu
- "--nic=" to select which net interface
- "--device=" to select which device
- :returns info: Success, decoded info
- :raises NotImplementedError: Error, not supported
- :raises Exceptions: Fail, with info
- """
- if para is None:
- return info
- else:
- err = NotImplementedError("Not supported decode: {}".format(para))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def format(self, info, fmt):
- """
- The inner method to format collected info.
-
- :param info: The decoded info
- :param fmt: The option for format,
- [raw, data, %s]:
- "raw" for original string
- "xml" for xml string
- "json" for json string
- "data" for list of decoded data string
- "table" for pretty table string
- :returns info: Success, formatted info
- :raises NotImplementedError: Error, not supported
- :raises Exceptions: Fail, with info
- """
- if (fmt == "raw"):
- return info
- elif (fmt == "data"):
- return info.split()
- else:
- err = NotImplementedError("Not supported format: {}".format(fmt))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- def output(self, info, path):
- """
- The method to output collected info to file.
-
- :param info: The formatted info
- :param path: The path to output, None for pass through
- :returns None: Success
- :returns info: Success, output info
- :raises: None
- """
- if path is None:
- return info
-
- f = open(path, mode='w', buffering=-1, encoding=None,
- errors=None, newline=None)
- f.write(info)
- f.close()
- return None
-
-
-def walk_class_type(father, class_type, desc, datas):
- if "class" in father and \
- father["class"] == class_type:
- if "description" in father and \
- (desc is None or father["description"] == desc):
- datas.append(father)
- return
- if "children" in father:
- for i in father["children"]:
- walk_class_type(i, class_type, desc, datas)
-
-
-def get_class_type(all, class_type, desc=None):
- datas = []
- walk_class_type(all, class_type, desc, datas)
- dict_datas = {}
- dict_datas[class_type + "s"] = datas
- return dict_datas
diff --git a/analysis/plugin/monitor/memory/__init__.py b/analysis/plugin/monitor/memory/__init__.py
deleted file mode 100755
index 0bcbc12..0000000
--- a/analysis/plugin/monitor/memory/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["numainfo", "topo", "bandwidth", "vmstat", "utilstat"]
-
-from . import *
diff --git a/analysis/plugin/monitor/memory/bandwidth.py b/analysis/plugin/monitor/memory/bandwidth.py
deleted file mode 100755
index b5c384a..0000000
--- a/analysis/plugin/monitor/memory/bandwidth.py
+++ /dev/null
@@ -1,236 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect memory bandwidth stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-import json
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-from monitor.memory import topo
-
-logger = logging.getLogger(__name__)
-
-
-class MemBandwidth(Monitor):
- """To collect memory bandwidth stat info"""
- _module = "MEM"
- _purpose = "BANDWIDTH"
- _option = "-a -e {events} --interval-print {int} --interval-count 1"
-
- __evs1620 = {
- "c0d0c0_r": "hisi_sccl1_ddrc0/flux_rd/",
- "c0d0c1_r": "hisi_sccl1_ddrc1/flux_rd/",
- "c0d0c2_r": "hisi_sccl1_ddrc2/flux_rd/",
- "c0d0c3_r": "hisi_sccl1_ddrc3/flux_rd/",
- "c0d0c0_w": "hisi_sccl1_ddrc0/flux_wr/",
- "c0d0c1_w": "hisi_sccl1_ddrc1/flux_wr/",
- "c0d0c2_w": "hisi_sccl1_ddrc2/flux_wr/",
- "c0d0c3_w": "hisi_sccl1_ddrc3/flux_wr/",
- "c0d1c0_r": "hisi_sccl3_ddrc0/flux_rd/",
- "c0d1c1_r": "hisi_sccl3_ddrc1/flux_rd/",
- "c0d1c2_r": "hisi_sccl3_ddrc2/flux_rd/",
- "c0d1c3_r": "hisi_sccl3_ddrc3/flux_rd/",
- "c0d1c0_w": "hisi_sccl3_ddrc0/flux_wr/",
- "c0d1c1_w": "hisi_sccl3_ddrc1/flux_wr/",
- "c0d1c2_w": "hisi_sccl3_ddrc2/flux_wr/",
- "c0d1c3_w": "hisi_sccl3_ddrc3/flux_wr/",
- "c1d0c0_r": "hisi_sccl5_ddrc0/flux_rd/",
- "c1d0c1_r": "hisi_sccl5_ddrc1/flux_rd/",
- "c1d0c2_r": "hisi_sccl5_ddrc2/flux_rd/",
- "c1d0c3_r": "hisi_sccl5_ddrc3/flux_rd/",
- "c1d0c0_w": "hisi_sccl5_ddrc0/flux_wr/",
- "c1d0c1_w": "hisi_sccl5_ddrc1/flux_wr/",
- "c1d0c2_w": "hisi_sccl5_ddrc2/flux_wr/",
- "c1d0c3_w": "hisi_sccl5_ddrc3/flux_wr/",
- "c1d1c0_r": "hisi_sccl7_ddrc0/flux_rd/",
- "c1d1c1_r": "hisi_sccl7_ddrc1/flux_rd/",
- "c1d1c2_r": "hisi_sccl7_ddrc2/flux_rd/",
- "c1d1c3_r": "hisi_sccl7_ddrc3/flux_rd/",
- "c1d1c0_w": "hisi_sccl7_ddrc0/flux_wr/",
- "c1d1c1_w": "hisi_sccl7_ddrc1/flux_wr/",
- "c1d1c2_w": "hisi_sccl7_ddrc2/flux_wr/",
- "c1d1c3_w": "hisi_sccl7_ddrc3/flux_wr/"}
-
- __cnt1620 = {
- "Total": 0,
- "CPU0": 0,
- "CPU1": 0,
- "CPU0_Die0": 0,
- "CPU0_Die1": 0,
- "CPU1_Die0": 0,
- "CPU1_Die1": 0,
- "CPU0_Die0_R": 0,
- "CPU0_Die1_R": 0,
- "CPU1_Die0_R": 0,
- "CPU1_Die1_R": 0,
- "CPU0_Die0_W": 0,
- "CPU0_Die1_W": 0,
- "CPU1_Die0_W": 0,
- "CPU1_Die1_W": 0,
- "Total_Max": 0,
- "CPU0_Max": 0,
- "CPU1_Max": 0,
- "Total_Util": 0}
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "perf stat"
- self.__interval = 1000
-
- self.__evs = self.__evs1620
- self.__cnt = self.__cnt1620
- self.__cnt["CPU0_Max"] = self.__get_theory_bandwidth(0) / 1024 / 1024
- self.__cnt["CPU1_Max"] = self.__get_theory_bandwidth(1) / 1024 / 1024
-
- self.__events = ""
- for e in self.__evs:
- self.__events = self.__events + self.__evs[e] + ","
- self.__events = self.__events.strip(",")
-
- help_info = "--fields="
- for c in self.__cnt:
- help_info = help_info + c + "/"
- help_info = help_info.strip("/")
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (help_info)
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val) * 1000
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval,
- events=self.__events)).split(),
- stderr=subprocess.STDOUT)
- return output.decode()
-
- def __get_theory_bandwidth(self, socket):
- memtopo = topo.MemTopo()
- info_json = memtopo.report("json", None)
- info = json.loads(info_json)
-
- width = 0
- dimms = [[0 for i in range(8)] for i in range(8)]
- for dimm in info["memorys"][0]["children"]:
- if dimm.get("size") is None:
- continue
- locator = memtopo._table_get_locator(dimm["slot"])
- if dimms[locator[0]][locator[1]] == 0:
- dimms[locator[0]][locator[1]] = dimm["width"] * \
- memtopo._table_get_freq(dimm["description"]) / 8
- ret = 0
- for channel in dimms[socket]:
- ret += channel
- return ret
-
- def __read_counters(self, c_evs):
- self.__cnt["CPU0_Die0_R"] = ((int(c_evs["c0d0c0_r"]) + int(c_evs["c0d0c1_r"]) + int(
- c_evs["c0d0c2_r"]) + int(c_evs["c0d0c3_r"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU0_Die1_R"] = ((int(c_evs["c0d1c0_r"]) + int(c_evs["c0d1c1_r"]) + int(
- c_evs["c0d1c2_r"]) + int(c_evs["c0d1c3_r"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU1_Die0_R"] = ((int(c_evs["c1d0c0_r"]) + int(c_evs["c1d0c1_r"]) + int(
- c_evs["c1d0c2_r"]) + int(c_evs["c1d0c3_r"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU1_Die1_R"] = ((int(c_evs["c1d1c0_r"]) + int(c_evs["c1d1c1_r"]) + int(
- c_evs["c1d1c2_r"]) + int(c_evs["c1d1c3_r"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU0_Die0_W"] = ((int(c_evs["c0d0c0_w"]) + int(c_evs["c0d0c1_w"]) + int(
- c_evs["c0d0c2_w"]) + int(c_evs["c0d0c3_w"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU0_Die1_W"] = ((int(c_evs["c0d1c0_w"]) + int(c_evs["c0d1c1_w"]) + int(
- c_evs["c0d1c2_w"]) + int(c_evs["c0d1c3_w"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU1_Die0_W"] = ((int(c_evs["c1d0c0_w"]) + int(c_evs["c1d0c1_w"]) + int(
- c_evs["c1d0c2_w"]) + int(c_evs["c1d0c3_w"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU1_Die1_W"] = ((int(c_evs["c1d1c0_w"]) + int(c_evs["c1d1c1_w"]) + int(
- c_evs["c1d1c2_w"]) + int(c_evs["c1d1c3_w"])) * 32 / 1024 / 1024) * 1000 / self.__interval
- self.__cnt["CPU0_Die0"] = self.__cnt["CPU0_Die0_R"] + \
- self.__cnt["CPU0_Die0_W"]
- self.__cnt["CPU0_Die1"] = self.__cnt["CPU0_Die1_R"] + \
- self.__cnt["CPU0_Die1_W"]
- self.__cnt["CPU1_Die0"] = self.__cnt["CPU1_Die0_R"] + \
- self.__cnt["CPU1_Die0_W"]
- self.__cnt["CPU1_Die1"] = self.__cnt["CPU1_Die1_R"] + \
- self.__cnt["CPU1_Die1_W"]
- self.__cnt["CPU0"] = self.__cnt["CPU0_Die0_R"] + self.__cnt["CPU0_Die0_W"] + \
- self.__cnt["CPU0_Die1_R"] + self.__cnt["CPU0_Die1_W"]
- self.__cnt["CPU1"] = self.__cnt["CPU1_Die0_R"] + self.__cnt["CPU1_Die0_W"] + \
- self.__cnt["CPU1_Die1_R"] + self.__cnt["CPU1_Die1_W"]
- self.__cnt["Total"] = self.__cnt["CPU0"] + self.__cnt["CPU1"]
- self.__cnt["Total_Max"] = self.__cnt["CPU0_Max"] + self.__cnt["CPU1_Max"]
- self.__cnt["Total_Util"] = self.__cnt["Total"] / self.__cnt["Total_Max"] * 100
-
- def decode(self, info, para):
- if para is None:
- return info
-
- c_evs = self.__evs.copy()
- for e in self.__evs:
- pattern = "^\ {2,}(\d.*?)\ {2,}(\d.*?)\ {2,}(" + \
- self.__evs[e] + ").*?"
- searchObj = re.search(pattern, info, re.ASCII | re.MULTILINE)
- if searchObj is not None:
- c_evs[e] = searchObj.group(2).replace(",", "")
- else:
- err = LookupError("Fail to find {}".format(self.__evs[e]))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- self.__read_counters(c_evs)
- fields = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- fields.append(val)
- continue
-
- for f in fields:
- ret = ret + " {:.2f}".format(self.__cnt[f])
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = MemBandwidth("UT")
-# help(ct)
- ct.report(sys.argv[1], sys.argv[2], "--interval=5;--fields=Total --fields=CPU0 --fields=CPU1 --fields=Total_Max --fields=CPU0_Max --fields=CPU1_Max --fields=Total_Util")
diff --git a/analysis/plugin/monitor/memory/numainfo.py b/analysis/plugin/monitor/memory/numainfo.py
deleted file mode 100755
index bf70443..0000000
--- a/analysis/plugin/monitor/memory/numainfo.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the memory numa info.
-"""
-
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class MemNuma(Monitor):
- """To collect the memory numa info"""
- _module = "MEM"
- _purpose = "NUMA"
- _option = "-H"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "numactl"
-
- def _get(self, para=None):
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split())
- return output.decode()
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = MemNuma("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/memory/topo.py b/analysis/plugin/monitor/memory/topo.py
deleted file mode 100755
index 39c10e3..0000000
--- a/analysis/plugin/monitor/memory/topo.py
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the memory topo.
-"""
-
-import sys
-import logging
-import subprocess
-import re
-import json
-import prettytable
-import dict2xml
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class MemTopo(Monitor):
- """To collect the memory topo"""
- _module = "MEM"
- _purpose = "TOPO"
- _option = "-c memory"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "lshw"
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("json, table")
-
- def _get(self, para=None):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=no_print)
- return output.decode()
-
- def __table_init(self, column):
- self.__columns = column
- data = ['Socket', 'Channel']
- for i in range(self.__columns):
- data.append("Slot {}".format(i))
- return prettytable.PrettyTable(data)
-
- def _table_get_locator(self, bank):
- pattern = re.compile(
- "DIMM.*?(\d)(\d)(\d)\s.*",
- re.ASCII | re.MULTILINE)
- scd = pattern.findall(bank)
- if len(scd) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- ret = []
- for i in scd[0]:
- ret.append(int(i))
- return ret
-
- def _table_get_freq(self, desc):
- pattern = re.compile(
- ".*?(\d+)\s([KMGT]?)Hz.*?",
- re.ASCII | re.MULTILINE)
- freq = pattern.findall(desc)
- if len(freq) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- if freq[-1][1] == "K":
- ret = int(freq[-1][0]) * 1000
- elif freq[-1][1] == "M":
- ret = int(freq[-1][0]) * 1000000
- elif freq[-1][1] == "G":
- ret = int(freq[-1][0]) * 1000000000
- elif freq[-1][1] == "T":
- ret = int(freq[-1][0]) * 1000000000000
- else:
- ret = int(freq[-1][0])
- return ret
-
- def __table_add_banks(self, table, datas, i, j):
- data = [i, j]
- for k in range(self.__columns):
- data.append(datas[i][j][k])
- table.add_row(data)
-
- def format(self, info, fmt):
- if (fmt == "json") or (fmt == "table") or (fmt == "xml"):
- o_json = subprocess.check_output("{cmd} -json".format(
- cmd=self.__cmd).split(), stderr=subprocess.DEVNULL)
- info = o_json.decode()
- all = json.loads(info)
-
- dict_datas = get_class_type(all, "memory", "System Memory")
- if (fmt == "json"):
- return json.dumps(dict_datas, indent=2)
- elif (fmt == "xml"):
- return dict2xml.dict2xml(dict_datas, "topology")
-
- dimms = [[["NO DIMM" for i in range(8)]
- for i in range(8)] for i in range(8)]
- max_socket = 0
- max_slot = 0
- max_channel = 0
- datas = dict_datas["memorys"]
- for data in datas:
- for bank in data["children"]:
- locator = self._table_get_locator(bank["slot"])
- if locator[0] > max_socket:
- max_socket = locator[0]
- if locator[1] > max_channel:
- max_channel = locator[1]
- if locator[2] > max_slot:
- max_slot = locator[2]
- if "size" in bank.keys():
- dimms[locator[0]][locator[1]][locator[2]] = "{} {} {} {}".format(
- bank["vendor"], bank["description"], bank["size"], bank["units"])
-
- tables = ""
- for socket in range(max_socket + 1):
- table = self.__table_init(max_slot + 1)
- for channel in range(max_channel + 1):
- self.__table_add_banks(table, dimms, socket, channel)
- tables += table.get_string(hrules=prettytable.ALL) + "\n\n"
- return tables
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = MemTopo("UT")
- print(ct.report(sys.argv[1], sys.argv[2]))
diff --git a/analysis/plugin/monitor/memory/utilstat.py b/analysis/plugin/monitor/memory/utilstat.py
deleted file mode 100755
index 9762480..0000000
--- a/analysis/plugin/monitor/memory/utilstat.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the mem util stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class MemUtilStat(Monitor):
- """To collect the mem util stat info"""
- _module = "MEM"
- _purpose = "UTIL"
- _option = "-r {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "sar"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--fields=time/kbmemfree/kbavail/kbmemused/memused/kbbuffers/kbcached/kbcommit/commit/kbactive/kbinact/kbdirty")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "kbmemfree": 1,
- "kbavail": 2,
- "kbmemused": 3,
- "memused": 4,
- "kbbuffers": 5,
- "kbcached": 6,
- "kbcommit": 7,
- "commit": 8,
- "kbactive": 9,
- "kbinact": 10,
- "kbdirty": 11}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*)\ {1,}(\d*)\ {2,}(\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- ret = ret + " " + searchObj[-1][i]
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = MemUtilStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--fields=kbmemfree --fields=memused --fields=kbdirty")
diff --git a/analysis/plugin/monitor/memory/vmstat.py b/analysis/plugin/monitor/memory/vmstat.py
deleted file mode 100755
index 218aedf..0000000
--- a/analysis/plugin/monitor/memory/vmstat.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the vm stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class MemVmstat(Monitor):
- """To collect the vm stat info"""
- _module = "MEM"
- _purpose = "VMSTAT"
- _option = "{int} 2"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "vmstat"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--fields=procs.r/procs.b/memory.swpd/memory.free/memory.buff/memory.cache/swap.si/swap.so/io.bi/io.bo/system.in/system.cs/cpu.us/cpu.sy/cpu.id/cpu.wa/cpu.st")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"procs.r": 0,
- "procs.b": 1,
- "memory.swpd": 2,
- "memory.free": 3,
- "memory.buff": 4,
- "memory.cache": 5,
- "swap.si": 6,
- "swap.so": 7,
- "io.bi": 8,
- "io.bo": 9,
- "system.in": 10,
- "system.cs": 11,
- "cpu.us": 12,
- "cpu.sy": 13,
- "cpu.id": 14,
- "cpu.wa": 15,
- "cpu.st": 16,
- "util.swap": "util.swap",
- "util.cpu": "util.cpu"}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^\ ?(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- if type(i).__name__ == 'int':
- ret = ret + " " + searchObj[-1][i]
- elif i == "util.swap":
- util = int(searchObj[-1][keyword["swap.si"]]) + \
- int(searchObj[-1][keyword["swap.so"]])
- ret = ret + " " + str(util)
- elif i == "util.cpu":
- util = int(searchObj[-1][keyword["cpu.us"]]) + \
- int(searchObj[-1][keyword["cpu.sy"]]) + \
- int(searchObj[-1][keyword["cpu.st"]])
- ret = ret + " " + str(util)
-
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = MemVmstat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--fields=memory.free --fields=cpu.us --fields=cpu.id --fields=util.cpu")
diff --git a/analysis/plugin/monitor/network/__init__.py b/analysis/plugin/monitor/network/__init__.py
deleted file mode 100755
index 9f16219..0000000
--- a/analysis/plugin/monitor/network/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["info", "netstat", "netestat", "topo"]
-
-from . import *
diff --git a/analysis/plugin/monitor/network/info.py b/analysis/plugin/monitor/network/info.py
deleted file mode 100755
index 2163e63..0000000
--- a/analysis/plugin/monitor/network/info.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the nic config info.
-"""
-
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class NetInfo(Monitor):
- """To collect the nic config info"""
- _module = "NET"
- _purpose = "INFO"
- _option = ";-l;-k"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "ethtool"
-
- def _get(self, para):
- opts = self._getopt()
- outputs = ""
- while True:
- try:
- output = subprocess.check_output("{cmd} {opt} {para}".format(
- cmd=self.__cmd, opt=next(opts), para=para).split())
- outputs += output.decode()
- except StopIteration:
- return outputs
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 4:
- print('usage: ' + sys.argv[0] + ' fmt path dev')
- sys.exit(-1)
- ct = NetInfo("UT")
- ct.report(sys.argv[1], sys.argv[2], sys.argv[3])
diff --git a/analysis/plugin/monitor/network/netestat.py b/analysis/plugin/monitor/network/netestat.py
deleted file mode 100755
index dd768e9..0000000
--- a/analysis/plugin/monitor/network/netestat.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the nic estat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class NetEStat(Monitor):
- """To collect the nic estat info"""
- _module = "NET"
- _purpose = "ESTAT"
- _option = "-n EDEV {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "sar"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--nic=x, --fields=time/nic/rxerrs/txerrs/colls/rxdrops/txdrops/txcarrs/rxframs/rxfifos/txfifos/errs/util")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "nic": 1,
- "rxerrs": 2,
- "txerrs": 3,
- "colls": 4,
- "rxdrops": 5,
- "txdrops": 6,
- "txcarrs": 7,
- "rxframs": 8,
- "rxfifos": 9,
- "txfifos": 10,
- "errs": "errs",
- "util": "util"}
-
- keys = []
- nic = "e.*?"
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['nic=', 'fields='])
- for opt, val in opts:
- if opt in ('--nic'):
- nic = val
- continue
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {1,}(" +
- nic +
- ")\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {2,}(\d*\.?\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data for {}".format(nic))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- if type(i).__name__ == 'int':
- ret = ret + " " + searchObj[-1][i]
- elif i == "errs":
- errs = float(searchObj[-1][keyword["rxerrs"]]) + \
- float(searchObj[-1][keyword["txerrs"]])
- ret = ret + " " + str(errs)
- elif i == "util":
- util = float(searchObj[-1][keyword["rxdrops"]]) + \
- float(searchObj[-1][keyword["txdrops"]]) + \
- float(searchObj[-1][keyword["rxfifos"]]) + \
- float(searchObj[-1][keyword["txfifos"]])
- ret = ret + " " + str(util)
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = NetEStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--nic=lo --fields=rxdrops --fields=txfifos --fields=util")
diff --git a/analysis/plugin/monitor/network/netstat.py b/analysis/plugin/monitor/network/netstat.py
deleted file mode 100755
index 4a26fb4..0000000
--- a/analysis/plugin/monitor/network/netstat.py
+++ /dev/null
@@ -1,126 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the nic stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class NetStat(Monitor):
- """To collect the nic stat info"""
- _module = "NET"
- _purpose = "STAT"
- _option = "-n DEV {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "sar"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--nic=x, --fields=time/nic/rxpcks/txpcks/rxkBs/txkBs/rxcmps/txcmps/rxmcsts/ifutil")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "nic": 1,
- "rxpcks": 2,
- "txpcks": 3,
- "rxkBs": 4,
- "txkBs": 5,
- "rxcmps": 6,
- "txcmps": 7,
- "rxmcsts": 8,
- "ifutil": 9}
-
- keys = []
- nic = "e.*?"
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['nic=', 'fields='])
- for opt, val in opts:
- if opt in ('--nic'):
- nic = val
- continue
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {1,}(" +
- nic +
- ")\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {2,}(\d*\.?\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data for {}".format(nic))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- ret = ret + " " + searchObj[-1][i]
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = NetStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--nic=lo --fields=txkBs --fields=rxkBs")
diff --git a/analysis/plugin/monitor/network/topo.py b/analysis/plugin/monitor/network/topo.py
deleted file mode 100755
index a40fb98..0000000
--- a/analysis/plugin/monitor/network/topo.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the nic topo.
-"""
-
-import sys
-import logging
-import subprocess
-import re
-import json
-import dict2xml
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class NetTopo(Monitor):
- """To collect the nic topo"""
- _module = "NET"
- _purpose = "TOPO"
- _option = "-c network"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "lshw"
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("xml, json")
-
- def _get(self, para=None):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=no_print)
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "json") or (fmt == "xml"):
- o_json = subprocess.check_output("{cmd} -json".format(
- cmd=self.__cmd).split(), stderr=subprocess.DEVNULL)
- info = o_json.decode()
- all = json.loads(info)
-
- dict_datas = get_class_type(all, "network")
- if (fmt == "json"):
- return json.dumps(dict_datas, indent=2)
- elif (fmt == "xml"):
- return dict2xml.dict2xml(dict_datas, "topology")
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = NetTopo("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/performance/__init__.py b/analysis/plugin/monitor/performance/__init__.py
deleted file mode 100755
index c72e2da..0000000
--- a/analysis/plugin/monitor/performance/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["stat", "top"]
-
-from . import *
diff --git a/analysis/plugin/monitor/performance/stat.py b/analysis/plugin/monitor/performance/stat.py
deleted file mode 100755
index f4c559d..0000000
--- a/analysis/plugin/monitor/performance/stat.py
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the perf stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class PerfStat(Monitor):
- """To collect the perf stat info"""
- _module = "PERF"
- _purpose = "STAT"
- _option = "-a -e cycles,instructions,branches,branch-misses,cache-misses,cache-references,dTLB-load-misses,dTLB-loads,iTLB-load-misses,iTLB-loads,stalled-cycles-backend,r7004,r7005 --interval-print {int} --interval-count 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "perf stat"
- self.__interval = 1000
-
- self.__stat = {
- "cycles": 0,
- "instructions": 0,
- "branches": 0,
- "branch-misses": 0,
- "cache-misses": 0,
- "cache-references": 0,
- "dTLB-load-misses": 0,
- "dTLB-loads": 0,
- "iTLB-load-misses": 0,
- "iTLB-loads": 0,
- "stalled-cycles-backend": 0,
- "memstall-load": 0,
- "memstall-store": 0,
- "IPC": 0,
- "BRANCH-MISS-RATIO": 0,
- "CACHE-MISS-RATIO": 0,
- "DTLB-LOAD-MISS-RATIO": 0,
- "ITLB-LOAD-MISS-RATIO": 0,
- "MPKI": 0,
- "SBPI": 0,
- "SBPC": 0,
- "MEMORY-BOUND": 0,
- "STORE-BOUND": 0}
-
- help_info = "--fields="
- for s in self.__stat:
- help_info = help_info + s + "/"
- help_info = help_info.strip("/")
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (help_info)
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val) * 1000
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split(),
- stderr=subprocess.STDOUT)
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "counts": 1,
- "unit": 2,
- "events": 3}
-
- eventmap = {"memstall-load": "r7004",
- "memstall-store": "r7005"}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(val)
- continue
-
- for s in self.__stat:
- event = eventmap.get(s)
- if event is None:
- event = s
- pattern = "^\ {2,}(\d.*?)\ {2,}(\d.*?)\ {2,}(\w*)\ {2,}(" + \
- event + ")\ {1,}.*"
- searchObj = re.search(pattern, info, re.ASCII | re.MULTILINE)
- if searchObj is not None:
- self.__stat[s] = int(
- searchObj.group(
- keyword["counts"] +
- 1).replace(
- ",",
- ""))
- else:
- self.__stat[s] = -1
-
- self.__stat["IPC"] = self.__stat["instructions"] / \
- self.__stat["cycles"]
- self.__stat["BRANCH-MISS-RATIO"] = self.__stat["branch-misses"] / \
- self.__stat["branches"] * 100
- self.__stat["CACHE-MISS-RATIO"] = self.__stat["cache-misses"] / \
- self.__stat["cache-references"] * 100
- self.__stat["DTLB-LOAD-MISS-RATIO"] = self.__stat["dTLB-load-misses"] / \
- self.__stat["dTLB-loads"] * 100
- self.__stat["ITLB-LOAD-MISS-RATIO"] = self.__stat["iTLB-load-misses"] / \
- self.__stat["iTLB-loads"] * 100
- self.__stat["MPKI"] = self.__stat["cache-misses"] / \
- self.__stat["instructions"] * 1000
- self.__stat["SBPI"] = self.__stat["instructions"] / \
- self.__stat["instructions"]
- self.__stat["SBPC"] = self.__stat["instructions"] / \
- self.__stat["cycles"]
- self.__stat["MEMORY-BOUND"] = (self.__stat["memstall-load"] +
- self.__stat["memstall-store"]) / \
- self.__stat["cycles"] * 100
- self.__stat["STORE-BOUND"] = self.__stat["memstall-store"] / \
- self.__stat["cycles"] * 100
-
- for event in keys:
- ret = ret + " " + str(self.__stat[event])
-
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = PerfStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=5;--fields=cycles --fields=instructions --fields=cache-misses --fields=MPKI --fields=MEMORY-BOUND")
diff --git a/analysis/plugin/monitor/performance/top.py b/analysis/plugin/monitor/performance/top.py
deleted file mode 100755
index ebe126a..0000000
--- a/analysis/plugin/monitor/performance/top.py
+++ /dev/null
@@ -1,191 +0,0 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the perf top snapshot.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-import random
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class PerfTop(Monitor):
- """To collect the perf top snapshot"""
- _module = "PERF"
- _purpose = "TOP"
- _option = "-a -e {event} sleep {int}"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__interval = 1
- self.__event = "cycles"
- self.__keyword = {"overhead": 0,
- "command": 1,
- "object": 2,
- "symbol": 3}
-
- help_info = "--interval, --event"
- self._get.__func__.__doc__ = Monitor._get.__doc__ % (help_info)
-
- help_info = "--fields="
- for f in self.__keyword:
- help_info = help_info + f + "/"
- help_info = help_info.strip("/")
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (help_info)
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(
- para.split(), None, [
- 'interval=', 'event='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
- elif opt in ('--event'):
- self.__event = val.split(",")[-1]
- continue
-
- data_file = "/tmp/perf{}".format(random.random())
- subprocess.check_output(
- "perf record -o {data} {opt}".format(
- opt=self._option.format(
- event=self.__event,
- int=self.__interval),
- data=data_file).split(),
- stderr=subprocess.DEVNULL)
- output = subprocess.check_output("perf report --stdio -i {data}".format(
- data=data_file).split(),
- stderr=subprocess.STDOUT)
- return output.decode()
-
- def __add_merge_entry(self, merge, entry, mask):
- entry = list(entry)
- entry[self.__keyword["overhead"]] = float(
- entry[self.__keyword["overhead"]])
- entry[self.__keyword["symbol"]] = int(
- entry[self.__keyword["symbol"]], 16)
-
- for i in range(len(merge)):
- if (merge[i][self.__keyword["command"]] == entry[self.__keyword["command"]]) and (
- merge[i][self.__keyword["object"]] == entry[self.__keyword["object"]]):
- entry_addr = entry[self.__keyword["symbol"]] & ~mask
- merged_addr = merge[i][self.__keyword["symbol"]] & ~mask
- if entry_addr == merged_addr:
- merge[i][self.__keyword["overhead"]
- ] += entry[self.__keyword["overhead"]]
- merge[i][self.__keyword["symbol"]] = merged_addr
- return
-
- merge.append(entry)
- return
-
- def __addr_merge(self, info, mask):
- merge = []
- i = 0
- while True:
- try:
- int(info[i][self.__keyword["symbol"]], 16)
- except ValueError:
- i += 1
- continue
- except IndexError:
- break
- self.__add_merge_entry(merge, info.pop(i), mask)
-
- for i in range(len(merge)):
- merge[i][self.__keyword["overhead"]
- ] = "%2.2f" % merge[i][self.__keyword["overhead"]]
- merge[i][self.__keyword["symbol"]
- ] = "0x%016x" % merge[i][self.__keyword["symbol"]]
- info.append(merge[i])
- return
-
- def decode(self, info, para):
- if para is None:
- return info
-
- pattern = re.compile(
- "^\ {2,}(\d.*?)%\ {2,}(\w.*?)\ {1,}(.*?)\ {2,}\[[.|k]\]\ (\w.*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- keys = []
- opts, args = getopt.getopt(
- para.split(), None, [
- 'fields=', 'addr-merge='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(val)
- continue
- elif opt in ('--addr-merge'):
- addr_mask = int(val, 16)
- continue
-
- self.__addr_merge(searchObj, addr_mask)
-
- ret = []
- for obj in searchObj:
- entry = []
- for event in keys:
- entry.append(obj[self.__keyword[event]])
- ret.append(entry)
- return ret
-
- def format(self, info, fmt):
- if (fmt == "raw"):
- return str(info)
- elif (fmt == "data"):
- return info
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = PerfTop("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2 --event=cycles;--fields=overhead --fields=symbol --addr-merge=0xffffffffffffffff")
diff --git a/analysis/plugin/monitor/processor/__init__.py b/analysis/plugin/monitor/processor/__init__.py
deleted file mode 100755
index a5b3c0b..0000000
--- a/analysis/plugin/monitor/processor/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["info", "stat", "topo"]
-
-from . import *
diff --git a/analysis/plugin/monitor/processor/info.py b/analysis/plugin/monitor/processor/info.py
deleted file mode 100755
index fb1ab73..0000000
--- a/analysis/plugin/monitor/processor/info.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the CPU info.
-"""
-
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class CpuInfo(Monitor):
- """To collect the CPU info"""
- _module = "CPU"
- _purpose = "INFO"
- _option = "-c processor"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "lshw"
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("xml, json")
-
- def _get(self, para=None):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=no_print)
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "xml"):
- o_xml = subprocess.check_output(
- "{cmd} -xml {opt}".format(
- cmd=self.__cmd,
- opt=self._option).split(),
- stderr=subprocess.DEVNULL)
- return o_xml.decode()
- elif (fmt == "json"):
- o_json = subprocess.check_output("{cmd} -json {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=subprocess.DEVNULL)
- return o_json.decode()
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = CpuInfo("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/processor/isolcpus.py b/analysis/plugin/monitor/processor/isolcpus.py
deleted file mode 100644
index 6811cfc..0000000
--- a/analysis/plugin/monitor/processor/isolcpus.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the CPU isolation info.
-"""
-import re
-import sys
-import subprocess
-from monitor.common import *
-
-
-class CpuIsolate(Monitor):
- """To collect the CPU isolation info"""
- _module = "CPU"
- _purpose = "ISOLATION"
- _path = "/proc/cmdline"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "cat"
-
- def _get(self, para=None):
- output = subprocess.check_output("{cmd} {path}".format(
- cmd=self.__cmd, path=self._path).split())
- return output.decode()
-
- def decode(self, info, para=None):
- """
- decode collected CPU isolation info.
-
- :param info: The collected info string
- :param para: The option for decode, para is None
- :returns info: decoded info
- """
- pattern = re.compile(r"isolcpus=([\d,]*)", re.MULTILINE)
- cpus = pattern.findall(info)
- return " ".join(cpus).strip()
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = CpuIsolate("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/processor/stat.py b/analysis/plugin/monitor/processor/stat.py
deleted file mode 100755
index 46da529..0000000
--- a/analysis/plugin/monitor/processor/stat.py
+++ /dev/null
@@ -1,183 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the CPU stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class CpuStat(Monitor):
- """To collect the CPU stat info"""
- _module = "CPU"
- _purpose = "STAT"
- _option = "-u -P ALL {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "mpstat"
- self.__interval = 1
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("json")
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--cpu=n, --fields=time/cpu/usr/nice/sys/iowait/irq/soft/steal/guest/gnice/idle")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "json"):
- o_json = subprocess.check_output(
- "{cmd} -o JSON {opt}".format(
- cmd=self.__cmd, opt=self._option.format(
- int=self.__interval)).split())
- return o_json.decode()
- else:
- return Monitor.format(self, info, fmt)
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "cpu": 1,
- "usr": 2,
- "nice": 3,
- "sys": 4,
- "iowait": 5,
- "irq": 6,
- "soft": 7,
- "steal": 8,
- "guest": 9,
- "gnice": 10,
- "idle": 11,
- "cutil": 12}
-
- keys = []
- cpu = -1 # -1 means all
- threshold = 0
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['cpu=', 'threshold=', 'fields='])
- for opt, val in opts:
- if opt in ('--cpu'):
- if val.isdigit():
- cpu = val
- else:
- err = ValueError("Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
- if opt in ('--threshold'):
- try:
- threshold = float(val)
- except ValueError:
- err = ValueError("Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {2,}(\d*|all)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)\ {2,}(\d*\.\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data for {}".format(cpu))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- stats = []
- for stat in searchObj:
- curr = list(stat)
- curr.append("{:.2f}".format(
- float(stat[keyword["usr"]]) + float(stat[keyword["nice"]]) +
- float(stat[keyword["sys"]]) + float(stat[keyword["irq"]]) +
- float(stat[keyword["soft"]]) + float(stat[keyword["steal"]])))
- stats.append(curr)
-
- if cpu == -1 and threshold > 0:
- cutil_sum = 0
- cutil_num = 0
- for i in range(1, len(stats)):
- if float(stats[i][keyword["cutil"]]) > threshold:
- cutil_sum += float(stats[i][keyword["cutil"]])
- cutil_num += 1
- if cutil_num == 0:
- stats[0][keyword["cutil"]] = "{:.2f}".format(cutil_sum)
- else:
- stats[0][keyword["cutil"]] = "{:.2f}".format(cutil_sum / cutil_num)
-
- for i in keys:
- ret = ret + " " + stats[cpu+1][i]
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = CpuStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--threshold=10.0 --fields=usr --fields=sys --fields=iowait --fields=irq --fields=guest")
diff --git a/analysis/plugin/monitor/processor/topo.py b/analysis/plugin/monitor/processor/topo.py
deleted file mode 100755
index aaa43a2..0000000
--- a/analysis/plugin/monitor/processor/topo.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the CPU topo.
-"""
-
-import sys
-import logging
-import subprocess
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class CpuTopo(Monitor):
- """To collect the CPU topo"""
- _module = "CPU"
- _purpose = "TOPO"
- _option = "--no-io --ignore misc"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("xml")
- with open('/dev/null', 'w') as no_print:
- if 0 == subprocess.call("which lstopo-no-graphics".split(),
- stdout=no_print, stderr=no_print):
- self.__cmd = "lstopo-no-graphics"
- elif 0 == subprocess.call("which lstopo".split(), stdout=no_print,
- stderr=no_print):
- self.__cmd = "lstopo"
-
- def _get(self, para=None):
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split())
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "xml"):
- o_xml = subprocess.check_output("{cmd} --of xml {opt}".format(
- cmd=self.__cmd, opt=self._option).split())
- return o_xml.decode()
- elif (fmt == "table"):
- o_xml = subprocess.check_output("{cmd} --of ascii {opt}".format(
- cmd=self.__cmd, opt=self._option).split())
- return o_xml.decode()
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = CpuTopo("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/storage/__init__.py b/analysis/plugin/monitor/storage/__init__.py
deleted file mode 100755
index 55799a1..0000000
--- a/analysis/plugin/monitor/storage/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-__all__ = ["iostat", "topo"]
-
-from . import *
diff --git a/analysis/plugin/monitor/storage/iostat.py b/analysis/plugin/monitor/storage/iostat.py
deleted file mode 100755
index f7ed149..0000000
--- a/analysis/plugin/monitor/storage/iostat.py
+++ /dev/null
@@ -1,143 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the storage stat info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class IoStat(Monitor):
- """To collect the storage stat info"""
- _module = "STORAGE"
- _purpose = "STAT"
- _option = "-xmt {int} 2"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "iostat"
- self.__interval = 1
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("json")
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--device=x, --fields=dev/rs/ws/rMBs/wMBs/rrqms/wrqms/rrqm/wrqm/r_await/w_await/aqu-sz/rareq-sz/wareq-sz/svctm/util")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "json"):
- o_json = subprocess.check_output(
- "{cmd} -o JSON {opt}".format(
- cmd=self.__cmd, opt=self._option.format(
- int=self.__interval)).split())
- return o_json.decode()
- else:
- return Monitor.format(self, info, fmt)
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"dev": 0,
- "rs": 1,
- "ws": 2,
- "rMBs": 3,
- "wMBs": 4,
- "rrqms": 5,
- "wrqms": 6,
- "rrqm": 7,
- "wrqm": 8,
- "r_await": 9,
- "w_await": 10,
- "aqu-sz": 11,
- "rareq-sz": 12,
- "wareq-sz": 13,
- "svctm": 14,
- "util": 15}
-
- keys = []
- dev = "sd.*?"
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['device=', 'fields='])
- for opt, val in opts:
- if opt in ('--device'):
- dev = val
- continue
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(" +
- dev +
- ")\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)\ {1,}(\d*\.\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data for {}".format(dev))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- ret = ret + " " + searchObj[-1][i]
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = IoStat("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--fields=wMBs --fields=rMBs")
diff --git a/analysis/plugin/monitor/storage/topo.py b/analysis/plugin/monitor/storage/topo.py
deleted file mode 100755
index f55f5df..0000000
--- a/analysis/plugin/monitor/storage/topo.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the storage topo.
-"""
-
-import sys
-import logging
-import subprocess
-import json
-import dict2xml
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class StorageTopo(Monitor):
- """To collect the storage topo"""
- _module = "STORAGE"
- _purpose = "TOPO"
- _option = "-c storage"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "lshw"
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("xml, json")
-
- def _get(self, para=None):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=no_print)
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "json") or (fmt == "xml"):
- o_json = subprocess.check_output("{cmd} -json".format(
- cmd=self.__cmd).split(), stderr=subprocess.DEVNULL)
- info = o_json.decode()
- all = json.loads(info)
-
- dict_datas = get_class_type(all, "storage")
- if (fmt == "json"):
- return json.dumps(dict_datas, indent=2)
- elif (fmt == "xml"):
- return dict2xml.dict2xml(dict_datas, "topology")
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = StorageTopo("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/system/__init__.py b/analysis/plugin/monitor/system/__init__.py
deleted file mode 100755
index 3171159..0000000
--- a/analysis/plugin/monitor/system/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The import content of the package.
-"""
-
-__all__ = ["bios", "ldavg", "tasks", "filed", "interrupts"]
-
-from . import *
diff --git a/analysis/plugin/monitor/system/bios.py b/analysis/plugin/monitor/system/bios.py
deleted file mode 100755
index 6220a3d..0000000
--- a/analysis/plugin/monitor/system/bios.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the system BIOS info.
-"""
-
-import sys
-import logging
-import subprocess
-import json
-import dict2xml
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class SysBiosInfo(Monitor):
- """To collect the system BIOS info"""
- _module = "SYS"
- _purpose = "BIOS"
- _option = "-c system"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "lshw"
- self.format.__func__.__doc__ = Monitor.format.__doc__ % ("xml, json")
-
- def _get(self, para=None):
- with open('/dev/null', 'w') as no_print:
- output = subprocess.check_output("{cmd} {opt}".format(
- cmd=self.__cmd, opt=self._option).split(),
- stderr=no_print)
- return output.decode()
-
- def format(self, info, fmt):
- if (fmt == "json") or (fmt == "xml"):
- o_json = subprocess.check_output("{cmd} -json".format(
- cmd=self.__cmd).split(), stderr=subprocess.DEVNULL)
- info = o_json.decode()
- all = json.loads(info)
-
- datas = []
- walk_class_type(all, "memory", "BIOS", datas)
- all.pop("children")
- datas.append(all)
- dict_datas = {}
- dict_datas["BIOS"] = datas
- if (fmt == "json"):
- return json.dumps(dict_datas, indent=2)
- elif (fmt == "xml"):
- return dict2xml.dict2xml(dict_datas, "info")
- else:
- return Monitor.format(self, info, fmt)
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = SysBiosInfo("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/system/filed.py b/analysis/plugin/monitor/system/filed.py
deleted file mode 100755
index 45ea7ab..0000000
--- a/analysis/plugin/monitor/system/filed.py
+++ /dev/null
@@ -1,96 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the file handles util info.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class SysFdUtil(Monitor):
- """To collect the file handles util info"""
- _module = "SYS"
- _purpose = "FDUTIL"
- _option = "/proc/sys/fs/file-nr"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--fields=allocated/pending/maximum/fd-util")
-
- def _get(self, para=None):
- with open(self._option, 'r') as f:
- fdinfo = f.read()
- return fdinfo
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"allocated": 0,
- "pending": 1,
- "maximum": 2,
- "fd-util": "fd-util"}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d*)\s{1,}(\d*)\s{1,}(\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- if type(i).__name__ == 'int':
- ret = ret + " " + searchObj[-1][i]
- elif i == "fd-util":
- util = int(searchObj[-1][keyword["allocated"]]) / \
- int(searchObj[-1][keyword["maximum"]]) * 100
- ret = ret + " " + str(util)
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = SysFdUtil("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- ";--fields=fd-util")
diff --git a/analysis/plugin/monitor/system/interrupts.py b/analysis/plugin/monitor/system/interrupts.py
deleted file mode 100644
index 3b8428a..0000000
--- a/analysis/plugin/monitor/system/interrupts.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the system device interrupts.
-"""
-import getopt
-import re
-import sys
-import subprocess
-from monitor.common import *
-
-
-class SysInterrupts(Monitor):
- """To collect the system device interrupts"""
- _module = "SYS"
- _purpose = "INTERRUPTS"
- _option = '{print$1$NF}'
- _path = "/proc/interrupts"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % "--nic=x"
- self.__cmd = "awk"
-
- def _get(self, para=None):
- output = subprocess.check_output("{cmd} {opt} {path}".format(
- cmd=self.__cmd, opt=self._option, path=self._path).split())
- return output.decode()
-
- def decode(self, info, para):
- """
- decode collected CPU interrupts info.
-
- :param info: The collected info string
- :param para: The option for decode,
- [%s]:
- "--nic=" to select which nic
- :returns info: decoded info
- """
- if para is None:
- pattern = re.compile(r"^(\d*):.*", re.MULTILINE)
- interrupts = pattern.findall(info)
- return " ".join(interrupts)
-
- nic = ""
- opts, _ = getopt.getopt(para.split(), None, ['nic='])
- for opt, val in opts:
- if opt in '--nic':
- nic = val
- break
-
- pattern = re.compile(r"^(\d*):{}$".format(nic.strip()), re.MULTILINE)
- interrupts = pattern.findall(info)
- return " ".join(interrupts).strip()
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = SysInterrupts("UT")
- ct.report(sys.argv[1], sys.argv[2])
diff --git a/analysis/plugin/monitor/system/ldavg.py b/analysis/plugin/monitor/system/ldavg.py
deleted file mode 100755
index 998421e..0000000
--- a/analysis/plugin/monitor/system/ldavg.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the system load average statistics.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class SysLdavg(Monitor):
- """To collect the system load average statistics"""
- _module = "SYS"
- _purpose = "LDAVG"
- _option = "-q {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "sar"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--fields=time/runq-sz/plist-sz/ldavg-1/ldavg-5/ldavg-15/blocked/task-util")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "runq-sz": 1,
- "plist-sz": 2,
- "ldavg-1": 3,
- "ldavg-5": 4,
- "ldavg-15": 5,
- "blocked": 6,
- "task-util": "task-util"}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {1,}(\d*)\ {1,}(\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)\ {1,}(\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- if type(i).__name__ == 'int':
- ret = ret + " " + searchObj[-1][i]
- elif i == "task-util":
- with open("/proc/sys/kernel/threads-max", 'r') as f:
- threads_max = f.read()
- util = int(searchObj[-1][keyword["plist-sz"]]) / \
- int(threads_max) * 100
- ret = ret + " " + str(util)
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = SysLdavg("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--fields=plist-sz --fields=ldavg-5 --fields=task-util")
diff --git a/analysis/plugin/monitor/system/tasks.py b/analysis/plugin/monitor/system/tasks.py
deleted file mode 100755
index 60e4ff2..0000000
--- a/analysis/plugin/monitor/system/tasks.py
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The sub class of the monitor, used to collect the task creation and switching statistics.
-"""
-
-import sys
-import logging
-import subprocess
-import getopt
-import re
-
-if __name__ == "__main__":
- sys.path.insert(0, "./../../")
-from monitor.common import *
-
-logger = logging.getLogger(__name__)
-
-
-class SysTasks(Monitor):
- """To collect the task creation and switching statistics"""
- _module = "SYS"
- _purpose = "TASKS"
- _option = "-w {int} 1"
-
- def __init__(self, user=None):
- Monitor.__init__(self, user)
- self.__cmd = "sar"
- self.__interval = 1
- self.decode.__func__.__doc__ = Monitor.decode.__doc__ % (
- "--fields=time/procs/cswchs")
-
- def _get(self, para=None):
- if para is not None:
- opts, args = getopt.getopt(para.split(), None, ['interval='])
- for opt, val in opts:
- if opt in ('--interval'):
- if val.isdigit():
- self.__interval = int(val)
- else:
- err = ValueError(
- "Invalid parameter: {opt}={val}".format(
- opt=opt, val=val))
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
- continue
-
- output = subprocess.check_output(
- "{cmd} {opt}".format(
- cmd=self.__cmd,
- opt=self._option.format(
- int=self.__interval)).split())
- return output.decode()
-
- def decode(self, info, para):
- if para is None:
- return info
-
- keyword = {"time": 0,
- "procs": 1,
- "cswchs": 2}
-
- keys = []
- ret = ""
-
- opts, args = getopt.getopt(para.split(), None, ['fields='])
- for opt, val in opts:
- if opt in ('--fields'):
- keys.append(keyword[val])
- continue
-
- pattern = re.compile(
- "^(\d.*?)\ {1,}(\d*\.?\d*)\ {1,}(\d*\.?\d*)",
- re.ASCII | re.MULTILINE)
- searchObj = pattern.findall(info)
- if len(searchObj) == 0:
- err = LookupError("Fail to find data")
- logger.error(
- "{}.{}: {}".format(
- self.__class__.__name__,
- sys._getframe().f_code.co_name,
- str(err)))
- raise err
-
- for i in keys:
- ret = ret + " " + searchObj[-1][i]
- return ret
-
-
-if __name__ == "__main__":
- if len(sys.argv) != 3:
- print('usage: ' + sys.argv[0] + ' fmt path')
- sys.exit(-1)
- ct = SysTasks("UT")
- ct.report(
- sys.argv[1],
- sys.argv[2],
- "--interval=2;--fields=procs --fields=cswchs")
diff --git a/analysis/plugin/plugin.py b/analysis/plugin/plugin.py
deleted file mode 100755
index dcf2f3b..0000000
--- a/analysis/plugin/plugin.py
+++ /dev/null
@@ -1,266 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The plugin for monitor and configurator.
-"""
-
-import sys
-import logging
-import os
-import threading
-import monitor
-import configurator
-import time
-
-logger = logging.getLogger(__name__)
-
-
-class ThreadedCall(threading.Thread):
- """class for function threaded calling"""
-
- def __init__(self, func, args=()):
- super(ThreadedCall, self).__init__()
- self.func = func
- self.args = args
-
- def run(self):
- self.result = self.func(*self.args)
-
- def get_result(self):
- threading.Thread.join(self)
- try:
- return self.result
- except Exception as err:
- return err
-
-
-class MPI:
- """The monitor plugin"""
-
- def __init__(self):
- """
- Initialize.
-
- :param: None
- :returns: None
- :raises: None
- """
- all_mpis = []
- all_modules = []
- all_purposes = []
- for m in monitor.common.Monitor.__subclasses__():
- all_mpis.append((m._module, m._purpose))
- all_modules.append(m._module)
- all_purposes.append(m._purpose)
- self.get_monitors.__func__.__doc__ = self.get_monitors.__func__.__doc__ % (
- set(all_modules), set(all_purposes))
- self.get_monitor.__func__.__doc__ = self.get_monitor.__func__.__doc__ % (
- all_mpis)
-
- @classmethod
- def get_monitors(self, module=None, purpose=None):
- """
- Get monitors of 'module' for 'purpose'.
-
- :param module(optional): %s
- :param purpose(optional): %s
- :returns list: Success, all found monitors or null
- :raises: None
- """
- mpis = []
- for m in monitor.common.Monitor.__subclasses__():
- if (module is not None) and (m._module != module):
- continue
- if (purpose is not None) and (m._purpose != purpose):
- continue
- me = m()
- mpis.append(me)
- return mpis
-
- @classmethod
- def get_monitor(self, module, purpose):
- """
- Get monitor of 'module' for 'purpose'.
-
- :param module & purpose: %s
- :returns mpi: Success, the found monitor
- :raises LookupError: Fail, find monitor error
- """
- mpis = MPI.get_monitors(module, purpose)
- if len(mpis) != 1:
- err = LookupError("Find {} {}-{} monitors".format(
- len(mpis), module, purpose))
- logger.error("MPI.{}: {}".format(
- sys._getframe().f_code.co_name, str(err)))
- raise err
- else:
- return mpis[0]
-
- @classmethod
- def get_monitor_pooled(self, module, purpose, pool):
- """
- Get monitor of 'module' for 'purpose' in pool.
-
- :param module & purpose: see get_monitor()
- :param pool: monitors pool for looking up
- :returns mpi: Success, the found monitor
- :raises LookupError: Fail, find monitor error
- """
- mpis = []
- for m in pool:
- if (module is not None) and (m._module != module):
- continue
- if (purpose is not None) and (m._purpose != purpose):
- continue
- mpis.append(m)
-
- if len(mpis) != 1:
- err = LookupError("Find {} {}-{} monitors in pool".format(
- len(mpis), module, purpose))
- logger.error("MPI.{}: {}".format(
- sys._getframe().f_code.co_name, str(err)))
- raise err
- else:
- return mpis[0]
-
- @classmethod
- def get_monitors_data(self, monitors, pool=None):
- """
- Get given monitors report data in one.
-
- :param monitors: ((module, purpose, options), ...)
- options is for report(para)
- :param pool: monitors pool for looking up
- :returns list: Success, decoded data strings of all given monitors
- :returns Exceptions: Success, formatted info
- :raises LookupError: Fail, find monitor error
- """
- mts = []
- for m in monitors:
- if pool is None:
- mon = MPI.get_monitor(m[0], m[1])
- else:
- mon = MPI.get_monitor_pooled(m[0], m[1], pool)
- mt = ThreadedCall(mon.report, ("data", None, m[2]))
- mts.append(mt)
- mt.start()
-
- rets = []
- for mt in mts:
- start = time.time()
- ret = mt.get_result()
- end = time.time()
- logger.debug("MPI.{}: Cost {} s to call {}, ret={}".format(
- sys._getframe().f_code.co_name, end-start, mt.func, str(ret)))
- if isinstance(ret, Exception):
- return ret
- rets += ret
- return rets
-
-
-class CPI:
- """The configurator plugin"""
-
- def __init__(self):
- """
- Initialize.
-
- :param: None
- :returns: None
- :raises: None
- """
- all_cpis = []
- all_modules = []
- all_submods = []
- for m in configurator.common.Configurator.__subclasses__():
- all_cpis.append((m._module, m._submod))
- all_modules.append(m._module)
- all_submods.append(m._submod)
- self.get_configurators.__func__.__doc__ = self.get_configurators.__func__.__doc__ % (
- set(all_modules), set(all_submods))
- self.get_configurator.__func__.__doc__ = self.get_configurator.__func__.__doc__ % (
- all_cpis)
-
- @classmethod
- def get_configurators(self, module=None, submod=None):
- """
- Get configurators of 'module'.'submod'.
-
- :param module(optional): %s
- :param submod(optional): %s
- :returns list: Success, all found configurators or null
- :raises: None
- """
- cpis = []
- for c in configurator.common.Configurator.__subclasses__():
- if (module is not None) and (c._module != module):
- continue
- if (submod is not None) and (c._submod != submod):
- continue
- ce = c()
- cpis.append(ce)
- return cpis
-
- @classmethod
- def get_configurator(self, module, submod):
- """
- Get configurator of 'module'.'submod'.
-
- :param module & submod: %s
- :returns cpi: Success, the found configurator
- :raises LookupError: Fail, find configurator error
- """
- cpis = CPI.get_configurators(module, submod)
- if len(cpis) != 1:
- err = LookupError("Find {} {}-{} configurators".format(
- len(cpis), module, submod))
- logger.error("CPI.{}: {}".format(
- sys._getframe().f_code.co_name, str(err)))
- raise err
- else:
- return cpis[0]
-
-
-# if __name__ == "__main__":
-# if len(sys.argv) == 4:
-# ret = MPI.get_monitors(sys.argv[1], sys.argv[2])
-# print(ret[0].get(sys.argv[3]))
-# elif len(sys.argv) == 3:
-# ret = MPI.get_monitors(sys.argv[1], sys.argv[2])
-# print(ret[0].get())
-# else:
-# print('usage: ' + sys.argv[0] + ' module purpose')
-
-# if __name__ == "__main__":
-# if len(sys.argv) == 3:
-# ret = CPI.get_configurators(sys.argv[1])
-# print(ret[0].set(sys.argv[2]))
-# else:
-# print('usage: ' + sys.argv[0] + ' module key=val')
-
-if __name__ == "__main__":
- monitors = (
- ("CPU",
- "STAT",
- "--interval=1;--cpu=1 --fields=usr --fields=sys --fields=iowait --fields=irq --fields=guest"),
- ("STORAGE",
- "STAT",
- "--interval=3;--device=sda --fields=rMBs --fields=wMBs"),
- ("NET",
- "STAT",
- "--interval=2;--nic=lo --fields=wKBs --fields=rKBs"),
- ("PERF",
- "STAT",
- "--interval=5;--fields=cycles --fields=instructions --fields=cache-misses"))
- print(MPI.get_monitors_data(monitors))
diff --git a/analysis/plugin/public.py b/analysis/plugin/public.py
deleted file mode 100755
index 2072a2a..0000000
--- a/analysis/plugin/public.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Custom exception and warning.
-"""
-
-
-class SetConfigError(Exception):
- """For setting config errors"""
- pass
-
-
-class GetConfigError(Exception):
- """For getting config errors"""
- pass
-
-
-class NeedRebootWarning(Warning):
- """For needing reboot after config"""
- pass
-
-
-class NeedConfigWarning(Warning):
- """For needing user handle after config"""
- pass
diff --git a/analysis/resources/__init__.py b/analysis/resources/__init__.py
deleted file mode 100644
index 23457e6..0000000
--- a/analysis/resources/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
diff --git a/analysis/resources/classification.py b/analysis/resources/classification.py
deleted file mode 100644
index 512009f..0000000
--- a/analysis/resources/classification.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for classification, in order to provide the method of post.
-"""
-
-from flask import abort
-from flask import current_app
-from flask_restful import Resource
-from flask_restful import marshal_with_field
-
-from optimizer.workload_characterization import WorkloadCharacterization
-from resources.field import classification_post_field
-from resources.parser import classification_post_parser
-from utils import utils
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class Classification(Resource):
- @marshal_with_field(classification_post_field)
- def post(self):
- args = classification_post_parser.parse_args()
- current_app.logger.info(args)
-
- model_path = args.get("modelpath")
- data_path = args.get("data")
- model = args.get("model", None)
- data = utils.readFromCsv(data_path)
- if not data:
- abort("data path may be not exist")
-
- classification = WorkloadCharacterization(model_path)
- resource_limit = ""
- if model is None:
- resource_limit, workload_type, percentage = classification.identify(data)
- else:
- workload_type, percentage = classification.reidentify(data, model)
-
- profile_name = {}
- profile_name["workload_type"] = workload_type
- profile_name["percentage"] = percentage
- profile_name["resource_limit"] = resource_limit
- return profile_name, 200
-
diff --git a/analysis/resources/collector.py b/analysis/resources/collector.py
deleted file mode 100755
index 7132073..0000000
--- a/analysis/resources/collector.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api with collector, in order to provide the method of post.
-"""
-
-from flask import current_app
-from flask_restful import reqparse, Resource
-from flask_restful import request, marshal_with, marshal_with_field
-import os
-import pandas as pd
-from resources.field import profile_get_field
-from resources.parser import collector_post_parser
-from plugin.plugin import CPI
-from plugin.plugin import MPI
-from utils.npipe import getNpipe
-
-parser = reqparse.RequestParser()
-
-
-class Collector(Resource):
- @marshal_with_field(profile_get_field)
- def post(self):
- args = collector_post_parser.parse_args()
- current_app.logger.info(args)
- monitors = []
- mpis = []
- for monitor in args.get("monitors"):
- monitors.append([monitor["module"], monitor["purpose"], monitor["field"]])
- mpis.append(MPI.get_monitor(monitor["module"], monitor["purpose"]))
- collect_num = args.get("sample_num")
-
- nPipe = getNpipe(args.get("pipe"))
- current_app.logger.info(monitors)
-
- data = []
-
- for i in range(collect_num):
- raw_data = MPI.get_monitors_data(monitors, mpis)
- current_app.logger.info(raw_data)
-
- float_data = list()
- for x in raw_data:
- float_data.append(float(x))
-
- data.append(float_data)
-
- str_data = [str(round(data, 3)) for data in float_data]
- nPipe.write(" ".join(str_data) + "\n")
-
- path = "/tmp/test.csv"
- save_file(path, data)
- result = {}
- result["path"] = path
- return result, 200
-
-
-def save_file(file_name, datas):
- print(datas)
- writer = pd.DataFrame(columns=None, data=datas)
- writer.to_csv(file_name, encoding='utf-8', header=0, index=False)
diff --git a/analysis/resources/configurator.py b/analysis/resources/configurator.py
deleted file mode 100755
index f11ed1b..0000000
--- a/analysis/resources/configurator.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for configurator, in order to provide the method of put and get.
-"""
-
-from flask import abort
-from flask import current_app
-from flask_restful import Resource
-from flask_restful import marshal_with_field
-from resources.parser import property_put_parser
-from resources.parser import configurator_get_parser
-from resources.field import configurator_put_field
-from plugin.plugin import CPI
-
-
-class Configurator(Resource):
- @marshal_with_field(configurator_put_field)
- def put(self):
- """
- calling cpi set method to set the value of the given key
- :param section: The section of the cpi
- :param key: the key to be set
- :param value: the value of the given key
- :returns status: the status return by the cpi set method
- :returns value: the message return by the cpi set method
- """
- result = {}
- args = property_put_parser.parse_args()
- current_app.logger.info(args)
- section = args.get("section").upper()
- modules = section.split(".")
- submodule = None
- if len(modules) > 1:
- submodule = modules[1]
- configurators = CPI.get_configurators(modules[0], submodule)
- if len(configurators) < 1:
- result["status"] = "module %s is not exist" % (section)
- return result, 200
- configurator = configurators[0]
-
- key = args.get("key")
- value = args.get("value")
- params = key + "=" + value
- ret = configurator.set(params)
- if not ret:
- result["status"] = "OK"
- elif isinstance(ret, Warning):
- result["status"] = "WARNING"
- result["value"] = str(ret)
- elif isinstance(ret, Exception):
- result["status"] = "ERROR"
- result["value"] = str(ret)
-
- return result, 200
-
- def get(self):
- """
- calling the cpi check method to check the value of the given key
- :param section: The section of the cpi
- :param key: the key to be get
- :param value: the expect value
- :returns status: the status compare the expect value with the real value
- :returns value: the system real value
- """
- result = {}
- args = configurator_get_parser.parse_args()
- current_app.logger.info(args)
- section = args.get("section").upper()
- key = args.get("key")
- value = args.get("value", "")
-
- modules = section.split(".")
- submodule = None
- if len(modules) > 1:
- submodule = modules[1]
- configurators = CPI.get_configurators(modules[0], submodule)
-
- if len(configurators) < 1:
- abort(404)
-
- configurator = configurators[0]
- realValue = configurator.get(key)
- result["value"] = realValue
- if realValue:
- if configurator._check(value, realValue):
- result["status"] = "OK"
- else:
- result["status"] = realValue
- else:
- result["status"] = "UNKNOWN"
-
- return result, 200
-
diff --git a/analysis/resources/field.py b/analysis/resources/field.py
deleted file mode 100644
index 4b75ac8..0000000
--- a/analysis/resources/field.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Fields used by restful api.
-"""
-
-from flask_restful import fields
-
-profile_field = {
- 'profile': fields.String,
-}
-
-profile_get_field = fields.Nested(profile_field)
-
-
-param_field = {
- 'status': fields.String,
- 'value': fields.String,
-}
-
-configurator_put_field = fields.Nested(param_field)
-
-optimizer_field = {
- 'status': fields.String
-}
-
-optimizer_post_field = {
- 'task_id': fields.String
-}
-
-classification_field = {
- 'resource_limit': fields.String,
- 'workload_type': fields.String,
- 'percentage': fields.Float,
-}
-
-classification_post_field = fields.Nested(classification_field)
diff --git a/analysis/resources/monitor.py b/analysis/resources/monitor.py
deleted file mode 100755
index b026ef9..0000000
--- a/analysis/resources/monitor.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for monitor, in order to provide the method of post and get.
-"""
-
-from flask import abort
-from flask import current_app
-from flask_restful import reqparse, Resource
-from resources.parser import monitor_get_parser
-from resources.parser import monitor_post_parser
-from plugin.plugin import MPI
-import getopt
-
-parser = reqparse.RequestParser()
-
-
-class Monitor(Resource):
- def get(self):
- result = {}
- args = monitor_get_parser.parse_args()
- current_app.logger.info(args)
- module = args.get("module")
- purpose = args.get("purpose", None)
- fmt = args.get("fmt")
- path = args.get("path")
- para = args.get("para")
-
- monitors = MPI.get_monitors(module, purpose)
- if len(monitors) < 1:
- return result, 200
-
- monitor = monitors[0]
-
- ret = monitor.report(fmt, path, para)
- if ret is not None:
- result["status"] = str(ret)
- else:
- result["status"] = "OK"
-
- return result, 200
-
- def post(self):
- result = {}
- args = monitor_post_parser.parse_args()
- current_app.logger.info(args)
-
- monitors = []
- module = args.get("module")
- purpose = args.get("purpose", None)
- field = args.get("field")
-
- monitors = MPI.get_monitors(module, purpose)
-
- if len(monitors) < 1:
- abort(404)
-
- monitor = monitors[0]
- ret = monitor.report("data", None, field)
- opts, args = getopt.getopt(field.split(";")[1].split(), None, ['fields=', 'addr-merge='])
- opt = []
- for o, v in opts:
- if o in ("--fields"):
- opt.append(v)
-
- events = []
- for index in range(len(ret)):
- if isinstance(ret[index], list):
- event = {}
- for i in range(len(ret[index])):
- event[opt[i]] = ret[index][i]
- events.append(event)
- else:
- result[opt[index]] = ret[index]
-
- if len(events) > 0:
- result["data"] = events
- return result, 200
-
diff --git a/analysis/resources/optimizer.py b/analysis/resources/optimizer.py
deleted file mode 100644
index 87ce2a2..0000000
--- a/analysis/resources/optimizer.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for optimizer, in order to provide the method of post, get, put and delete.
-"""
-from flask import Flask, abort
-from flask import current_app
-from flask_restful import reqparse, Resource
-from flask_restful import request, marshal_with, marshal_with_field
-import os
-import uuid
-from multiprocessing import Queue, Pipe
-
-import resources.optimizer
-from resources.field import optimizer_post_field
-from resources.parser import optimizer_post_parser
-from resources.parser import optimizer_put_parser
-from optimizer import optimizer
-from utils import task_cache
-import logging
-
-logger = logging.getLogger(__name__)
-
-parser = reqparse.RequestParser()
-
-
-class Optimizer(Resource):
- def get(self, task_id=None):
- result = []
- if not task_id:
- tasks_all = task_cache.TasksCache.getInstance().get_all()
- for task in tasks_all:
- result.append(task)
- else:
- task = task_cache.TasksCache.getInstance().get(task_id)
- if not task:
- abort(404, "taskid {0} not found".format(task_id))
- result.append(task_id)
- return result, 200
-
- # @marshal_with_field(optimizdder_post_field)
- def post(self):
- args = optimizer_post_parser.parse_args()
- logger.info(args)
-
- if args["max_eval"] < 10:
- abort(400, "max_eval must be >=10")
- task_id = str(uuid.uuid1())
-
- parent_conn, child_conn = Pipe()
- engine = optimizer.Optimizer(task_id, args["knobs"], child_conn, max_eval=args.get("max_eval"))
- engine.start()
-
- value = {}
- value["process"] = engine
- value["pipe"] = parent_conn
- task_cache.TasksCache.getInstance().set(task_id, value)
-
- result = {}
-
- result["task_id"] = task_id
- return result, 201
-
- def put(self, task_id):
- if not task_id:
- abort(404)
- task = task_cache.TasksCache.getInstance().get(task_id)
- if not task:
- abort(404, "taskid {0} not found".format(task_id))
-
- args = optimizer_put_parser.parse_args()
- logger.info(args)
- out_queue = task["pipe"]
- if args["iterations"] != 0:
- out_queue.send(args.get("value"))
-
- result = {}
- values = out_queue.recv()
- params = ["%s=%s" % (k, v) for k, v in values.items()]
- result["param"] = ",".join(params)
-
- return result, 200
-
- def delete(self, task_id):
- if not task_id:
- abort(404)
- process = task_cache.TasksCache.getInstance().get(task_id)
- if not process:
- abort(404, "taskid {0} not found".format(task_id))
- process["process"].stopProcess()
- task_cache.TasksCache.getInstance().get(task_id)["pipe"].close()
-
- process = task_cache.TasksCache.getInstance().delete(task_id)
- return {}, 200
-
diff --git a/analysis/resources/parser.py b/analysis/resources/parser.py
deleted file mode 100644
index 7cf58a6..0000000
--- a/analysis/resources/parser.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Parameters used for restful api.
-"""
-
-from flask_restful import reqparse
-
-
-analysis_post_parser = reqparse.RequestParser()
-analysis_post_parser.add_argument('appname', required=True, help="The appname to be analysed")
-analysis_post_parser.add_argument('pipe', required=True,
- help="The pipe name to send process status")
-analysis_post_parser.add_argument('workload', required=True, help="The workload dict info")
-analysis_post_parser.add_argument('algorithm', required=True, help="The algorithm to be selected")
-analysis_post_parser.add_argument('modelpath', required=True, help="The modelfile to be used")
-analysis_post_parser.add_argument('scaler', required=True, help="The scalerfile to be used")
-analysis_post_parser.add_argument('encoder', required=True, help="The encoderfile to be used")
-
-property_put_parser = reqparse.RequestParser()
-property_put_parser.add_argument('section', required=True, help="The section to be configured")
-property_put_parser.add_argument('key', required=True, help="The property to be configured")
-property_put_parser.add_argument('value', required=True, help="The value to be configured")
-
-configurator_get_parser = reqparse.RequestParser()
-configurator_get_parser.add_argument('section', required=True, help="The section to be configured")
-configurator_get_parser.add_argument('key', required=True, help="The property to be configured")
-configurator_get_parser.add_argument('value', required=False, help="The value to be configured")
-
-monitor_get_parser = reqparse.RequestParser()
-monitor_get_parser.add_argument('module', required=True, help="The module to be monitor")
-monitor_get_parser.add_argument('purpose', required=True, help="The purpose of the module")
-monitor_get_parser.add_argument('fmt', required=True, help="The format of the result")
-monitor_get_parser.add_argument('path', required=True, help="The path to be generated")
-monitor_get_parser.add_argument('para', required=True, help="The parameter of get method")
-
-monitor_post_parser = reqparse.RequestParser()
-monitor_post_parser.add_argument('module', required=True, help="The module to be monitor")
-monitor_post_parser.add_argument('purpose', required=True, help="The purpose of the module")
-monitor_post_parser.add_argument('field', required=True, help="The field of the monitor")
-
-optimizer_post_parser = reqparse.RequestParser()
-optimizer_post_parser.add_argument('max_eval', type=int, required=True,
- help="max_eval cannot be null")
-optimizer_post_parser.add_argument('knobs', type=list, location='json',
- help="knobs list cannot be null")
-
-optimizer_put_parser = reqparse.RequestParser()
-optimizer_put_parser.add_argument('iterations', type=int, required=True,
- help="iterations cannot be null")
-optimizer_put_parser.add_argument('value', type=str, required=True, help="value cannot be null")
-
-collector_post_parser = reqparse.RequestParser()
-collector_post_parser.add_argument('sample_num', type=int, required=True,
- help="the numbers to be collections")
-collector_post_parser.add_argument('monitors', type=list, location='json',
- help="knobs list cannot be null")
-collector_post_parser.add_argument('pipe', required=True,
- help="The pipe name to send process status")
-
-classification_post_parser = reqparse.RequestParser()
-classification_post_parser.add_argument('modelpath', required=True, help="The modelfile to be used")
-classification_post_parser.add_argument('data', help="The data path to be used")
-classification_post_parser.add_argument('model', help="The model self trained to be used")
-
-
-profile_get_parser = reqparse.RequestParser()
-profile_get_parser.add_argument('section', required=True, help="The section to be configured")
-profile_get_parser.add_argument('config', required=True, help="The config to be get")
-profile_get_parser.add_argument('path', required=True, help="The path to backup to")
-
-profile_put_parser = reqparse.RequestParser()
-profile_put_parser.add_argument('section', required=True, help="The section to be configured")
-profile_put_parser.add_argument('config', required=True, help="The config to be get")
-
-train_post_parser = reqparse.RequestParser()
-train_post_parser.add_argument('datapath', required=True, help="The datapath can not be null")
-train_post_parser.add_argument('outputpath', required=True, help="The output path can not be null")
-train_post_parser.add_argument('modelpath', required=True, help="The model path can not be null")
diff --git a/analysis/resources/profile.py b/analysis/resources/profile.py
deleted file mode 100755
index 2dba975..0000000
--- a/analysis/resources/profile.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for profile, in order to provide the method of get and put.
-"""
-
-from flask import abort
-from flask import current_app
-from flask_restful import Resource
-from resources.parser import profile_get_parser, profile_put_parser
-from plugin.plugin import CPI
-
-
-class Profile(Resource):
- '''
- resume the profile
- '''
-
- def put(self):
- result = {}
- args = profile_put_parser.parse_args()
- current_app.logger.info(args)
- section = args.get("section").upper()
- modules = section.split(".")
- submodule = None
- if len(modules) > 1:
- submodule = modules[1]
- configurators = CPI.get_configurators(modules[0], submodule)
- if len(configurators) < 1:
- abort(404)
-
- configurator = configurators[0]
-
- config = args.get("config")
- ret = configurator.resume(config)
- if ret is not None:
- result["status"] = str(ret)
- else:
- result["status"] = "OK"
-
- return result, 200
-
- '''
- backup the profile
- '''
-
- def get(self):
- result = {}
- args = profile_get_parser.parse_args()
- current_app.logger.info(args)
- section = args.get("section").upper()
- config = args.get("config")
- backupDir = args.get("path")
-
- modules = section.split(".")
- submodule = None
- if len(modules) > 1:
- submodule = modules[1]
- configurators = CPI.get_configurators(modules[0], submodule)
-
- if len(configurators) < 1:
- abort(404)
-
- configurator = configurators[0]
- realValue = configurator.backup(config, backupDir)
- if isinstance(realValue, Exception):
- result["status"] = "FAILED"
- result["value"] = "exception"
- else:
- if not realValue:
- result["status"] = "FAILED"
- result["value"] = "UNKNOWN"
- else:
- result["status"] = "SUCCESS"
- result["value"] = realValue
-
- return result, 200
-
diff --git a/analysis/resources/train.py b/analysis/resources/train.py
deleted file mode 100644
index c1b94a9..0000000
--- a/analysis/resources/train.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Restful api for training, in order to provide the method of post.
-"""
-
-from flask import abort
-from flask_restful import Resource
-
-from optimizer.workload_characterization import WorkloadCharacterization
-from resources.parser import train_post_parser
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class Training(Resource):
- def post(self):
- args = train_post_parser.parse_args()
- logger.info(args)
-
- model_path = args.get("modelpath")
- output_path = args.get("outputpath")
- data_path = args.get("datapath")
-
- charaterization = WorkloadCharacterization(model_path)
- try:
- charaterization.retrain(data_path, output_path)
- except Exception as err:
- logger.error(err)
- abort(500)
-
- return {}, 200
diff --git a/analysis/utils/__init__.py b/analysis/utils/__init__.py
deleted file mode 100644
index 23457e6..0000000
--- a/analysis/utils/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
diff --git a/analysis/utils/npipe.py b/analysis/utils/npipe.py
deleted file mode 100644
index da275d4..0000000
--- a/analysis/utils/npipe.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Pipe used to send status to golang process.
-"""
-
-import os
-import time
-
-
-class NPipe():
- #pipe used to send status to golang process
- def __init__(self, pipe_name, pipe_mode = os.O_SYNC | os.O_CREAT | os.O_WRONLY):
- self.pipe = pipe_name
- self.pipe_mode = pipe_mode
- self.f = None
-
- def write(self, message):
- print("send message:", self.f, message)
- if not isinstance(message, str):
- return None
- message = message.encode()
- length = os.write(self.f, message)
- return length
-
- def open(self):
- if not os.path.exists(self.pipe):
- return None
- self.f = os.open(self.pipe, self.pipe_mode)
- return self.f
-
- def __del__(self):
- self.close()
-
- def close(self):
- if not self.f:
- return
- os.close(self.f)
-
-
-def getNpipe(pipe, pipe_mode=None):
- npipe = NPipe(pipe)
- f = npipe.open()
- print(f)
- if not f:
- return None
- else:
- return npipe
-
-
-if __name__ == "__main__":
- npipe = getNpipe("/tmp/pipe.ipc")
- if not npipe:
- print("pipe is none")
- exit(1)
- npipe.write("just a npipe test")
diff --git a/analysis/utils/task_cache.py b/analysis/utils/task_cache.py
deleted file mode 100644
index 11032f5..0000000
--- a/analysis/utils/task_cache.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Used to create tasks for optimizer.
-"""
-
-
-class TasksCache(object):
- tasks = {}
-
- #以下类方法,用于单例模式
- __instance = None
-
- def __new__(cls, *args, **kwargs):
- if cls.__instance is None:
- cls.__instance = super(TasksCache, cls).__new__(cls, *args, **kwargs)
- return cls.__instance
-
- @classmethod
- def getInstance(cls):
- if(cls.__instance is None):
- cls.__instance = TasksCache()
- return cls.__instance
-
- def get(self, key, default=None):
- return self.tasks.get(key) if key in self.tasks.keys() else None
-
- def set(self, key, value):
- self.tasks[key] = value
-
- def delete(self, key):
- del self.tasks[key]
-
- def get_all(self):
- return self.tasks
diff --git a/analysis/utils/utils.py b/analysis/utils/utils.py
deleted file mode 100644
index dd89d1f..0000000
--- a/analysis/utils/utils.py
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Provide an interface to read data from csv.
-"""
-
-import os
-import pandas as pd
-import numpy as np
-
-
-def readFromCsv(path):
- if not os.path.exists(path):
- return None
- if not path.endswith('.csv'):
- return None
-
- f = open(path, 'r')
- data = pd.read_csv(f)
- data = np.array(data).tolist()
-
- return data
-
diff --git a/api/profile/profile.pb.go b/api/profile/profile.pb.go
deleted file mode 100644
index 43ddc8c..0000000
--- a/api/profile/profile.pb.go
+++ /dev/null
@@ -1,1333 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: profile.proto
-
-/*
-Package profile is a generated protocol buffer package.
-
-It is generated from these files:
- profile.proto
-
-It has these top-level messages:
- ListMessage
- ProfileInfo
- AnalysisMessage
- Ack
- AckCheck
- ProfileLog
- CollectFlag
- TrainMessage
- DefineMessage
- ScheduleMessage
-*/
-package profile
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
-
-type ListMessage struct {
- WorkloadType string `protobuf:"bytes,1,opt,name=WorkloadType" json:"WorkloadType,omitempty"`
- ProfileNames string `protobuf:"bytes,2,opt,name=ProfileNames" json:"ProfileNames,omitempty"`
- Active string `protobuf:"bytes,3,opt,name=Active" json:"Active,omitempty"`
-}
-
-func (m *ListMessage) Reset() { *m = ListMessage{} }
-func (m *ListMessage) String() string { return proto.CompactTextString(m) }
-func (*ListMessage) ProtoMessage() {}
-func (*ListMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-
-func (m *ListMessage) GetWorkloadType() string {
- if m != nil {
- return m.WorkloadType
- }
- return ""
-}
-
-func (m *ListMessage) GetProfileNames() string {
- if m != nil {
- return m.ProfileNames
- }
- return ""
-}
-
-func (m *ListMessage) GetActive() string {
- if m != nil {
- return m.Active
- }
- return ""
-}
-
-type ProfileInfo struct {
- Name string `protobuf:"bytes,1,opt,name=Name" json:"Name,omitempty"`
- Content []byte `protobuf:"bytes,2,opt,name=Content,proto3" json:"Content,omitempty"`
-}
-
-func (m *ProfileInfo) Reset() { *m = ProfileInfo{} }
-func (m *ProfileInfo) String() string { return proto.CompactTextString(m) }
-func (*ProfileInfo) ProtoMessage() {}
-func (*ProfileInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-
-func (m *ProfileInfo) GetName() string {
- if m != nil {
- return m.Name
- }
- return ""
-}
-
-func (m *ProfileInfo) GetContent() []byte {
- if m != nil {
- return m.Content
- }
- return nil
-}
-
-type AnalysisMessage struct {
- Name string `protobuf:"bytes,1,opt,name=Name" json:"Name,omitempty"`
- Model string `protobuf:"bytes,2,opt,name=Model" json:"Model,omitempty"`
-}
-
-func (m *AnalysisMessage) Reset() { *m = AnalysisMessage{} }
-func (m *AnalysisMessage) String() string { return proto.CompactTextString(m) }
-func (*AnalysisMessage) ProtoMessage() {}
-func (*AnalysisMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-
-func (m *AnalysisMessage) GetName() string {
- if m != nil {
- return m.Name
- }
- return ""
-}
-
-func (m *AnalysisMessage) GetModel() string {
- if m != nil {
- return m.Model
- }
- return ""
-}
-
-type Ack struct {
- Status string `protobuf:"bytes,1,opt,name=Status" json:"Status,omitempty"`
-}
-
-func (m *Ack) Reset() { *m = Ack{} }
-func (m *Ack) String() string { return proto.CompactTextString(m) }
-func (*Ack) ProtoMessage() {}
-func (*Ack) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
-
-func (m *Ack) GetStatus() string {
- if m != nil {
- return m.Status
- }
- return ""
-}
-
-type AckCheck struct {
- Name string `protobuf:"bytes,1,opt,name=Name" json:"Name,omitempty"`
- Status string `protobuf:"bytes,2,opt,name=Status" json:"Status,omitempty"`
- Description string `protobuf:"bytes,3,opt,name=Description" json:"Description,omitempty"`
-}
-
-func (m *AckCheck) Reset() { *m = AckCheck{} }
-func (m *AckCheck) String() string { return proto.CompactTextString(m) }
-func (*AckCheck) ProtoMessage() {}
-func (*AckCheck) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
-
-func (m *AckCheck) GetName() string {
- if m != nil {
- return m.Name
- }
- return ""
-}
-
-func (m *AckCheck) GetStatus() string {
- if m != nil {
- return m.Status
- }
- return ""
-}
-
-func (m *AckCheck) GetDescription() string {
- if m != nil {
- return m.Description
- }
- return ""
-}
-
-type ProfileLog struct {
- Id int64 `protobuf:"varint,1,opt,name=Id" json:"Id,omitempty"`
- ProfileId string `protobuf:"bytes,2,opt,name=ProfileId" json:"ProfileId,omitempty"`
- Timestamp string `protobuf:"bytes,3,opt,name=Timestamp" json:"Timestamp,omitempty"`
-}
-
-func (m *ProfileLog) Reset() { *m = ProfileLog{} }
-func (m *ProfileLog) String() string { return proto.CompactTextString(m) }
-func (*ProfileLog) ProtoMessage() {}
-func (*ProfileLog) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
-
-func (m *ProfileLog) GetId() int64 {
- if m != nil {
- return m.Id
- }
- return 0
-}
-
-func (m *ProfileLog) GetProfileId() string {
- if m != nil {
- return m.ProfileId
- }
- return ""
-}
-
-func (m *ProfileLog) GetTimestamp() string {
- if m != nil {
- return m.Timestamp
- }
- return ""
-}
-
-type CollectFlag struct {
- Interval int64 `protobuf:"varint,1,opt,name=Interval" json:"Interval,omitempty"`
- Duration int64 `protobuf:"varint,2,opt,name=Duration" json:"Duration,omitempty"`
- Workload string `protobuf:"bytes,3,opt,name=Workload" json:"Workload,omitempty"`
- OutputPath string `protobuf:"bytes,4,opt,name=OutputPath" json:"OutputPath,omitempty"`
- Block string `protobuf:"bytes,5,opt,name=Block" json:"Block,omitempty"`
- Network string `protobuf:"bytes,6,opt,name=Network" json:"Network,omitempty"`
- Type string `protobuf:"bytes,7,opt,name=Type" json:"Type,omitempty"`
-}
-
-func (m *CollectFlag) Reset() { *m = CollectFlag{} }
-func (m *CollectFlag) String() string { return proto.CompactTextString(m) }
-func (*CollectFlag) ProtoMessage() {}
-func (*CollectFlag) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
-
-func (m *CollectFlag) GetInterval() int64 {
- if m != nil {
- return m.Interval
- }
- return 0
-}
-
-func (m *CollectFlag) GetDuration() int64 {
- if m != nil {
- return m.Duration
- }
- return 0
-}
-
-func (m *CollectFlag) GetWorkload() string {
- if m != nil {
- return m.Workload
- }
- return ""
-}
-
-func (m *CollectFlag) GetOutputPath() string {
- if m != nil {
- return m.OutputPath
- }
- return ""
-}
-
-func (m *CollectFlag) GetBlock() string {
- if m != nil {
- return m.Block
- }
- return ""
-}
-
-func (m *CollectFlag) GetNetwork() string {
- if m != nil {
- return m.Network
- }
- return ""
-}
-
-func (m *CollectFlag) GetType() string {
- if m != nil {
- return m.Type
- }
- return ""
-}
-
-type TrainMessage struct {
- DataPath string `protobuf:"bytes,1,opt,name=DataPath" json:"DataPath,omitempty"`
- OutputPath string `protobuf:"bytes,2,opt,name=OutputPath" json:"OutputPath,omitempty"`
-}
-
-func (m *TrainMessage) Reset() { *m = TrainMessage{} }
-func (m *TrainMessage) String() string { return proto.CompactTextString(m) }
-func (*TrainMessage) ProtoMessage() {}
-func (*TrainMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
-
-func (m *TrainMessage) GetDataPath() string {
- if m != nil {
- return m.DataPath
- }
- return ""
-}
-
-func (m *TrainMessage) GetOutputPath() string {
- if m != nil {
- return m.OutputPath
- }
- return ""
-}
-
-type DefineMessage struct {
- WorkloadType string `protobuf:"bytes,1,opt,name=WorkloadType" json:"WorkloadType,omitempty"`
- ProfileName string `protobuf:"bytes,2,opt,name=ProfileName" json:"ProfileName,omitempty"`
- Content []byte `protobuf:"bytes,3,opt,name=Content,proto3" json:"Content,omitempty"`
-}
-
-func (m *DefineMessage) Reset() { *m = DefineMessage{} }
-func (m *DefineMessage) String() string { return proto.CompactTextString(m) }
-func (*DefineMessage) ProtoMessage() {}
-func (*DefineMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
-
-func (m *DefineMessage) GetWorkloadType() string {
- if m != nil {
- return m.WorkloadType
- }
- return ""
-}
-
-func (m *DefineMessage) GetProfileName() string {
- if m != nil {
- return m.ProfileName
- }
- return ""
-}
-
-func (m *DefineMessage) GetContent() []byte {
- if m != nil {
- return m.Content
- }
- return nil
-}
-
-type ScheduleMessage struct {
- App string `protobuf:"bytes,1,opt,name=App" json:"App,omitempty"`
- Type string `protobuf:"bytes,2,opt,name=Type" json:"Type,omitempty"`
- Strategy string `protobuf:"bytes,3,opt,name=Strategy" json:"Strategy,omitempty"`
-}
-
-func (m *ScheduleMessage) Reset() { *m = ScheduleMessage{} }
-func (m *ScheduleMessage) String() string { return proto.CompactTextString(m) }
-func (*ScheduleMessage) ProtoMessage() {}
-func (*ScheduleMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
-
-func (m *ScheduleMessage) GetApp() string {
- if m != nil {
- return m.App
- }
- return ""
-}
-
-func (m *ScheduleMessage) GetType() string {
- if m != nil {
- return m.Type
- }
- return ""
-}
-
-func (m *ScheduleMessage) GetStrategy() string {
- if m != nil {
- return m.Strategy
- }
- return ""
-}
-
-func init() {
- proto.RegisterType((*ListMessage)(nil), "profile.ListMessage")
- proto.RegisterType((*ProfileInfo)(nil), "profile.ProfileInfo")
- proto.RegisterType((*AnalysisMessage)(nil), "profile.AnalysisMessage")
- proto.RegisterType((*Ack)(nil), "profile.Ack")
- proto.RegisterType((*AckCheck)(nil), "profile.AckCheck")
- proto.RegisterType((*ProfileLog)(nil), "profile.ProfileLog")
- proto.RegisterType((*CollectFlag)(nil), "profile.CollectFlag")
- proto.RegisterType((*TrainMessage)(nil), "profile.TrainMessage")
- proto.RegisterType((*DefineMessage)(nil), "profile.DefineMessage")
- proto.RegisterType((*ScheduleMessage)(nil), "profile.ScheduleMessage")
-}
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the grpc package it is being compiled against.
-const _ = grpc.SupportPackageIsVersion4
-
-// Client API for ProfileMgr service
-
-type ProfileMgrClient interface {
- Profile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ProfileClient, error)
- CheckInitProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CheckInitProfileClient, error)
- Analysis(ctx context.Context, in *AnalysisMessage, opts ...grpc.CallOption) (ProfileMgr_AnalysisClient, error)
- Tuning(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_TuningClient, error)
- ListWorkload(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ListWorkloadClient, error)
- UpgradeProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_UpgradeProfileClient, error)
- InfoProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_InfoProfileClient, error)
- CheckActiveProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CheckActiveProfileClient, error)
- ProfileRollback(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ProfileRollbackClient, error)
- Charaterization(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CharaterizationClient, error)
- Collection(ctx context.Context, in *CollectFlag, opts ...grpc.CallOption) (ProfileMgr_CollectionClient, error)
- Training(ctx context.Context, in *TrainMessage, opts ...grpc.CallOption) (ProfileMgr_TrainingClient, error)
- Define(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error)
- Delete(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error)
- Update(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error)
- Schedule(ctx context.Context, in *ScheduleMessage, opts ...grpc.CallOption) (ProfileMgr_ScheduleClient, error)
-}
-
-type profileMgrClient struct {
- cc *grpc.ClientConn
-}
-
-func NewProfileMgrClient(cc *grpc.ClientConn) ProfileMgrClient {
- return &profileMgrClient{cc}
-}
-
-func (c *profileMgrClient) Profile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ProfileClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[0], c.cc, "/profile.ProfileMgr/Profile", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrProfileClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_ProfileClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrProfileClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrProfileClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) CheckInitProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CheckInitProfileClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[1], c.cc, "/profile.ProfileMgr/CheckInitProfile", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrCheckInitProfileClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_CheckInitProfileClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrCheckInitProfileClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrCheckInitProfileClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Analysis(ctx context.Context, in *AnalysisMessage, opts ...grpc.CallOption) (ProfileMgr_AnalysisClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[2], c.cc, "/profile.ProfileMgr/Analysis", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrAnalysisClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_AnalysisClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrAnalysisClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrAnalysisClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Tuning(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_TuningClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[3], c.cc, "/profile.ProfileMgr/Tuning", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrTuningClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_TuningClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrTuningClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrTuningClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) ListWorkload(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ListWorkloadClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[4], c.cc, "/profile.ProfileMgr/ListWorkload", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrListWorkloadClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_ListWorkloadClient interface {
- Recv() (*ListMessage, error)
- grpc.ClientStream
-}
-
-type profileMgrListWorkloadClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrListWorkloadClient) Recv() (*ListMessage, error) {
- m := new(ListMessage)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) UpgradeProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_UpgradeProfileClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[5], c.cc, "/profile.ProfileMgr/UpgradeProfile", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrUpgradeProfileClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_UpgradeProfileClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrUpgradeProfileClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrUpgradeProfileClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) InfoProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_InfoProfileClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[6], c.cc, "/profile.ProfileMgr/InfoProfile", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrInfoProfileClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_InfoProfileClient interface {
- Recv() (*ProfileInfo, error)
- grpc.ClientStream
-}
-
-type profileMgrInfoProfileClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrInfoProfileClient) Recv() (*ProfileInfo, error) {
- m := new(ProfileInfo)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) CheckActiveProfile(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CheckActiveProfileClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[7], c.cc, "/profile.ProfileMgr/CheckActiveProfile", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrCheckActiveProfileClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_CheckActiveProfileClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrCheckActiveProfileClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrCheckActiveProfileClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) ProfileRollback(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_ProfileRollbackClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[8], c.cc, "/profile.ProfileMgr/ProfileRollback", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrProfileRollbackClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_ProfileRollbackClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrProfileRollbackClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrProfileRollbackClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Charaterization(ctx context.Context, in *ProfileInfo, opts ...grpc.CallOption) (ProfileMgr_CharaterizationClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[9], c.cc, "/profile.ProfileMgr/Charaterization", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrCharaterizationClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_CharaterizationClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrCharaterizationClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrCharaterizationClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Collection(ctx context.Context, in *CollectFlag, opts ...grpc.CallOption) (ProfileMgr_CollectionClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[10], c.cc, "/profile.ProfileMgr/Collection", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrCollectionClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_CollectionClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrCollectionClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrCollectionClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Training(ctx context.Context, in *TrainMessage, opts ...grpc.CallOption) (ProfileMgr_TrainingClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[11], c.cc, "/profile.ProfileMgr/Training", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrTrainingClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_TrainingClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrTrainingClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrTrainingClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *profileMgrClient) Define(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error) {
- out := new(Ack)
- err := grpc.Invoke(ctx, "/profile.ProfileMgr/Define", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *profileMgrClient) Delete(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error) {
- out := new(Ack)
- err := grpc.Invoke(ctx, "/profile.ProfileMgr/Delete", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *profileMgrClient) Update(ctx context.Context, in *DefineMessage, opts ...grpc.CallOption) (*Ack, error) {
- out := new(Ack)
- err := grpc.Invoke(ctx, "/profile.ProfileMgr/Update", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *profileMgrClient) Schedule(ctx context.Context, in *ScheduleMessage, opts ...grpc.CallOption) (ProfileMgr_ScheduleClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_ProfileMgr_serviceDesc.Streams[12], c.cc, "/profile.ProfileMgr/Schedule", opts...)
- if err != nil {
- return nil, err
- }
- x := &profileMgrScheduleClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type ProfileMgr_ScheduleClient interface {
- Recv() (*AckCheck, error)
- grpc.ClientStream
-}
-
-type profileMgrScheduleClient struct {
- grpc.ClientStream
-}
-
-func (x *profileMgrScheduleClient) Recv() (*AckCheck, error) {
- m := new(AckCheck)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for ProfileMgr service
-
-type ProfileMgrServer interface {
- Profile(*ProfileInfo, ProfileMgr_ProfileServer) error
- CheckInitProfile(*ProfileInfo, ProfileMgr_CheckInitProfileServer) error
- Analysis(*AnalysisMessage, ProfileMgr_AnalysisServer) error
- Tuning(*ProfileInfo, ProfileMgr_TuningServer) error
- ListWorkload(*ProfileInfo, ProfileMgr_ListWorkloadServer) error
- UpgradeProfile(*ProfileInfo, ProfileMgr_UpgradeProfileServer) error
- InfoProfile(*ProfileInfo, ProfileMgr_InfoProfileServer) error
- CheckActiveProfile(*ProfileInfo, ProfileMgr_CheckActiveProfileServer) error
- ProfileRollback(*ProfileInfo, ProfileMgr_ProfileRollbackServer) error
- Charaterization(*ProfileInfo, ProfileMgr_CharaterizationServer) error
- Collection(*CollectFlag, ProfileMgr_CollectionServer) error
- Training(*TrainMessage, ProfileMgr_TrainingServer) error
- Define(context.Context, *DefineMessage) (*Ack, error)
- Delete(context.Context, *DefineMessage) (*Ack, error)
- Update(context.Context, *DefineMessage) (*Ack, error)
- Schedule(*ScheduleMessage, ProfileMgr_ScheduleServer) error
-}
-
-func RegisterProfileMgrServer(s *grpc.Server, srv ProfileMgrServer) {
- s.RegisterService(&_ProfileMgr_serviceDesc, srv)
-}
-
-func _ProfileMgr_Profile_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Profile(m, &profileMgrProfileServer{stream})
-}
-
-type ProfileMgr_ProfileServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrProfileServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrProfileServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_CheckInitProfile_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).CheckInitProfile(m, &profileMgrCheckInitProfileServer{stream})
-}
-
-type ProfileMgr_CheckInitProfileServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrCheckInitProfileServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrCheckInitProfileServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Analysis_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(AnalysisMessage)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Analysis(m, &profileMgrAnalysisServer{stream})
-}
-
-type ProfileMgr_AnalysisServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrAnalysisServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrAnalysisServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Tuning_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Tuning(m, &profileMgrTuningServer{stream})
-}
-
-type ProfileMgr_TuningServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrTuningServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrTuningServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_ListWorkload_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).ListWorkload(m, &profileMgrListWorkloadServer{stream})
-}
-
-type ProfileMgr_ListWorkloadServer interface {
- Send(*ListMessage) error
- grpc.ServerStream
-}
-
-type profileMgrListWorkloadServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrListWorkloadServer) Send(m *ListMessage) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_UpgradeProfile_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).UpgradeProfile(m, &profileMgrUpgradeProfileServer{stream})
-}
-
-type ProfileMgr_UpgradeProfileServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrUpgradeProfileServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrUpgradeProfileServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_InfoProfile_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).InfoProfile(m, &profileMgrInfoProfileServer{stream})
-}
-
-type ProfileMgr_InfoProfileServer interface {
- Send(*ProfileInfo) error
- grpc.ServerStream
-}
-
-type profileMgrInfoProfileServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrInfoProfileServer) Send(m *ProfileInfo) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_CheckActiveProfile_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).CheckActiveProfile(m, &profileMgrCheckActiveProfileServer{stream})
-}
-
-type ProfileMgr_CheckActiveProfileServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrCheckActiveProfileServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrCheckActiveProfileServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_ProfileRollback_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).ProfileRollback(m, &profileMgrProfileRollbackServer{stream})
-}
-
-type ProfileMgr_ProfileRollbackServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrProfileRollbackServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrProfileRollbackServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Charaterization_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ProfileInfo)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Charaterization(m, &profileMgrCharaterizationServer{stream})
-}
-
-type ProfileMgr_CharaterizationServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrCharaterizationServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrCharaterizationServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Collection_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(CollectFlag)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Collection(m, &profileMgrCollectionServer{stream})
-}
-
-type ProfileMgr_CollectionServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrCollectionServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrCollectionServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Training_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(TrainMessage)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Training(m, &profileMgrTrainingServer{stream})
-}
-
-type ProfileMgr_TrainingServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrTrainingServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrTrainingServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _ProfileMgr_Define_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(DefineMessage)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(ProfileMgrServer).Define(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/profile.ProfileMgr/Define",
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(ProfileMgrServer).Define(ctx, req.(*DefineMessage))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _ProfileMgr_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(DefineMessage)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(ProfileMgrServer).Delete(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/profile.ProfileMgr/Delete",
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(ProfileMgrServer).Delete(ctx, req.(*DefineMessage))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _ProfileMgr_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
- in := new(DefineMessage)
- if err := dec(in); err != nil {
- return nil, err
- }
- if interceptor == nil {
- return srv.(ProfileMgrServer).Update(ctx, in)
- }
- info := &grpc.UnaryServerInfo{
- Server: srv,
- FullMethod: "/profile.ProfileMgr/Update",
- }
- handler := func(ctx context.Context, req interface{}) (interface{}, error) {
- return srv.(ProfileMgrServer).Update(ctx, req.(*DefineMessage))
- }
- return interceptor(ctx, in, info, handler)
-}
-
-func _ProfileMgr_Schedule_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(ScheduleMessage)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(ProfileMgrServer).Schedule(m, &profileMgrScheduleServer{stream})
-}
-
-type ProfileMgr_ScheduleServer interface {
- Send(*AckCheck) error
- grpc.ServerStream
-}
-
-type profileMgrScheduleServer struct {
- grpc.ServerStream
-}
-
-func (x *profileMgrScheduleServer) Send(m *AckCheck) error {
- return x.ServerStream.SendMsg(m)
-}
-
-var _ProfileMgr_serviceDesc = grpc.ServiceDesc{
- ServiceName: "profile.ProfileMgr",
- HandlerType: (*ProfileMgrServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "Define",
- Handler: _ProfileMgr_Define_Handler,
- },
- {
- MethodName: "Delete",
- Handler: _ProfileMgr_Delete_Handler,
- },
- {
- MethodName: "Update",
- Handler: _ProfileMgr_Update_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "Profile",
- Handler: _ProfileMgr_Profile_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "CheckInitProfile",
- Handler: _ProfileMgr_CheckInitProfile_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Analysis",
- Handler: _ProfileMgr_Analysis_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Tuning",
- Handler: _ProfileMgr_Tuning_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "ListWorkload",
- Handler: _ProfileMgr_ListWorkload_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "UpgradeProfile",
- Handler: _ProfileMgr_UpgradeProfile_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "InfoProfile",
- Handler: _ProfileMgr_InfoProfile_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "CheckActiveProfile",
- Handler: _ProfileMgr_CheckActiveProfile_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "ProfileRollback",
- Handler: _ProfileMgr_ProfileRollback_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Charaterization",
- Handler: _ProfileMgr_Charaterization_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Collection",
- Handler: _ProfileMgr_Collection_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Training",
- Handler: _ProfileMgr_Training_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "Schedule",
- Handler: _ProfileMgr_Schedule_Handler,
- ServerStreams: true,
- },
- },
- Metadata: "profile.proto",
-}
-
-func init() { proto.RegisterFile("profile.proto", fileDescriptor0) }
-
-var fileDescriptor0 = []byte{
- // 656 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0x5b, 0x4b, 0x1b, 0x41,
- 0x14, 0x36, 0x1b, 0x4d, 0xe2, 0x49, 0xbc, 0x74, 0xb0, 0xb2, 0x48, 0x5b, 0x64, 0x9f, 0xfa, 0x24,
- 0xd2, 0xd2, 0xd2, 0x12, 0xb4, 0xa4, 0x91, 0x42, 0x8a, 0x5a, 0x49, 0x22, 0xf5, 0x75, 0xdc, 0x1d,
- 0x37, 0xcb, 0x4e, 0x76, 0x96, 0xd9, 0x89, 0xc5, 0xfe, 0xbc, 0x42, 0xff, 0x57, 0x99, 0xdb, 0x66,
- 0x22, 0x49, 0x61, 0xf3, 0xb6, 0xdf, 0x39, 0xe7, 0x3b, 0xf7, 0x33, 0x0b, 0x3b, 0x39, 0x67, 0x0f,
- 0x09, 0x25, 0x27, 0x39, 0x67, 0x82, 0xa1, 0xa6, 0x81, 0xc1, 0x14, 0xda, 0x97, 0x49, 0x21, 0xae,
- 0x48, 0x51, 0xe0, 0x98, 0xa0, 0x00, 0x3a, 0x3f, 0x19, 0x4f, 0x29, 0xc3, 0xd1, 0xf8, 0x29, 0x27,
- 0x7e, 0xed, 0xb8, 0xf6, 0x76, 0x7b, 0xb8, 0x20, 0x93, 0x36, 0x37, 0x9a, 0x7d, 0x8d, 0xa7, 0xa4,
- 0xf0, 0x3d, 0x6d, 0xe3, 0xca, 0xd0, 0x21, 0x34, 0x7a, 0xa1, 0x48, 0x1e, 0x89, 0x5f, 0x57, 0x5a,
- 0x83, 0x82, 0x2e, 0xb4, 0x8d, 0xdd, 0x20, 0x7b, 0x60, 0x08, 0xc1, 0xa6, 0xb4, 0x37, 0x61, 0xd4,
- 0x37, 0xf2, 0xa1, 0xd9, 0x67, 0x99, 0x20, 0x99, 0x50, 0x9e, 0x3b, 0x43, 0x0b, 0x83, 0x2e, 0xec,
- 0xf5, 0x32, 0x4c, 0x9f, 0x8a, 0xa4, 0xb0, 0xf9, 0x2e, 0x73, 0x70, 0x00, 0x5b, 0x57, 0x2c, 0x22,
- 0xd4, 0x24, 0xa6, 0x41, 0xf0, 0x1a, 0xea, 0xbd, 0x30, 0x95, 0x89, 0x8d, 0x04, 0x16, 0xb3, 0xc2,
- 0x50, 0x0c, 0x0a, 0xee, 0xa0, 0xd5, 0x0b, 0xd3, 0xfe, 0x84, 0x84, 0xe9, 0x52, 0xa7, 0x73, 0x9e,
- 0xe7, 0xf2, 0xd0, 0x31, 0xb4, 0x2f, 0x48, 0x11, 0xf2, 0x24, 0x17, 0x09, 0xcb, 0x4c, 0xb5, 0xae,
- 0x28, 0xb8, 0x03, 0x30, 0x25, 0x5f, 0xb2, 0x18, 0xed, 0x82, 0x37, 0x88, 0x94, 0xe7, 0xfa, 0xd0,
- 0x1b, 0x44, 0xe8, 0x15, 0x6c, 0xdb, 0x86, 0x44, 0xc6, 0xf5, 0x5c, 0x20, 0xb5, 0xe3, 0x64, 0x4a,
- 0x0a, 0x81, 0xa7, 0xb9, 0xf1, 0x3d, 0x17, 0x04, 0x7f, 0x6b, 0xd0, 0xee, 0x33, 0x4a, 0x49, 0x28,
- 0xbe, 0x51, 0x1c, 0xa3, 0x23, 0x68, 0x0d, 0x32, 0x41, 0xf8, 0x23, 0xa6, 0x26, 0x42, 0x89, 0xa5,
- 0xee, 0x62, 0xc6, 0xb1, 0x4a, 0xd2, 0xd3, 0x3a, 0x8b, 0xa5, 0xce, 0x0e, 0xd8, 0x04, 0x29, 0x31,
- 0x7a, 0x03, 0xf0, 0x63, 0x26, 0xf2, 0x99, 0xb8, 0xc1, 0x62, 0xe2, 0x6f, 0x2a, 0xad, 0x23, 0x91,
- 0xcd, 0xfe, 0x4a, 0x59, 0x98, 0xfa, 0x5b, 0xba, 0xd9, 0x0a, 0xc8, 0x19, 0x5e, 0x13, 0xf1, 0x8b,
- 0xf1, 0xd4, 0x6f, 0x28, 0xb9, 0x85, 0xb2, 0xb7, 0x6a, 0xb1, 0x9a, 0xba, 0xb7, 0xf2, 0x3b, 0xf8,
- 0x0e, 0x9d, 0x31, 0xc7, 0x49, 0x66, 0x87, 0x2a, 0x73, 0xc5, 0x02, 0xab, 0x88, 0x7a, 0x06, 0x25,
- 0x7e, 0x96, 0x8f, 0xf7, 0x3c, 0x9f, 0x80, 0xc1, 0xce, 0x05, 0x79, 0x48, 0x32, 0x52, 0x65, 0xa3,
- 0x8f, 0xcb, 0xad, 0x54, 0x73, 0xd7, 0x5e, 0x5d, 0x91, 0xbb, 0x94, 0xf5, 0xc5, 0xa5, 0x1c, 0xc1,
- 0xde, 0x28, 0x9c, 0x90, 0x68, 0x46, 0xcb, 0x90, 0xfb, 0x50, 0xef, 0xe5, 0xb9, 0x89, 0x24, 0x3f,
- 0xcb, 0xaa, 0xbd, 0x79, 0xd5, 0xb2, 0xca, 0x91, 0xe0, 0x58, 0x90, 0xf8, 0xc9, 0x76, 0xdd, 0xe2,
- 0x77, 0x7f, 0x9a, 0xe5, 0xd2, 0x5c, 0xc5, 0x1c, 0x7d, 0x84, 0xa6, 0x41, 0xe8, 0xe0, 0xc4, 0x1e,
- 0xb2, 0x73, 0x47, 0x47, 0x2f, 0x4a, 0xa9, 0x5d, 0xe2, 0x60, 0xe3, 0xb4, 0x86, 0xbe, 0xc0, 0xbe,
- 0x02, 0x83, 0x2c, 0x11, 0x6b, 0x39, 0xe8, 0x42, 0xcb, 0x5e, 0x1c, 0xf2, 0xe7, 0x26, 0x8b, 0x47,
- 0xb8, 0x8a, 0xfc, 0x01, 0x1a, 0xe3, 0x59, 0x96, 0x64, 0x71, 0xb5, 0x98, 0xe7, 0xd0, 0x91, 0x2f,
- 0x52, 0xb9, 0x81, 0xcb, 0xc9, 0x73, 0xa9, 0xf3, 0x7c, 0x29, 0xfe, 0x19, 0xec, 0xde, 0xe6, 0x31,
- 0xc7, 0x11, 0x59, 0xab, 0xe4, 0x33, 0x68, 0x4b, 0xf5, 0xff, 0xb9, 0x4b, 0xa5, 0x8a, 0xde, 0x03,
- 0xa4, 0x7c, 0xe9, 0xf7, 0x6e, 0xad, 0x0c, 0xce, 0x61, 0xcf, 0x58, 0x0d, 0x19, 0xa5, 0xf7, 0x38,
- 0x4c, 0x2b, 0xf3, 0xfb, 0x13, 0x2c, 0x37, 0x89, 0x27, 0xbf, 0xf5, 0x85, 0x57, 0xe2, 0x7f, 0x06,
- 0x30, 0xaf, 0xca, 0x22, 0xd5, 0x79, 0x6a, 0x56, 0x51, 0x3f, 0x41, 0x4b, 0x5d, 0xb2, 0x1c, 0xfa,
- 0xcb, 0xd2, 0xc4, 0x3d, 0xee, 0x55, 0xcc, 0x53, 0x68, 0xe8, 0xbb, 0x45, 0x87, 0xa5, 0xc1, 0xc2,
- 0x21, 0x1f, 0x75, 0x5c, 0x62, 0xb0, 0xa1, 0x19, 0x94, 0x88, 0x4a, 0x8c, 0xdb, 0x3c, 0xc2, 0x15,
- 0x18, 0x5d, 0x68, 0xd9, 0xe3, 0x76, 0xf6, 0xff, 0xd9, 0xbd, 0xaf, 0x28, 0xe9, 0xbe, 0xa1, 0x7e,
- 0xb5, 0xef, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0xcf, 0x76, 0xaf, 0x46, 0x7b, 0x07, 0x00, 0x00,
-}
diff --git a/api/profile/profile.proto b/api/profile/profile.proto
deleted file mode 100755
index 0383c1a..0000000
--- a/api/profile/profile.proto
+++ /dev/null
@@ -1,82 +0,0 @@
-syntax = "proto3";
-
-package profile;
-
-// The transporter service definition.
-service ProfileMgr {
- rpc Profile(ProfileInfo) returns (stream AckCheck) {}
- rpc CheckInitProfile(ProfileInfo) returns (stream AckCheck) {}
- rpc Analysis(AnalysisMessage) returns (stream AckCheck) {}
- rpc Tuning(ProfileInfo) returns (stream AckCheck) {}
- rpc ListWorkload(ProfileInfo) returns (stream ListMessage) {}
- rpc UpgradeProfile(ProfileInfo) returns (stream AckCheck) {}
- rpc InfoProfile(ProfileInfo) returns (stream ProfileInfo) {}
- rpc CheckActiveProfile(ProfileInfo) returns (stream AckCheck) {}
- rpc ProfileRollback(ProfileInfo) returns (stream AckCheck) {}
- rpc Charaterization(ProfileInfo) returns (stream AckCheck) {}
- rpc Collection(CollectFlag) returns (stream AckCheck) {}
- rpc Training(TrainMessage) returns (stream AckCheck) {}
- rpc Define(DefineMessage) returns (Ack) {}
- rpc Delete(DefineMessage) returns (Ack) {}
- rpc Update(DefineMessage) returns (Ack) {}
- rpc Schedule(ScheduleMessage) returns (stream AckCheck) {}
-}
-
-message ListMessage {
- string WorkloadType = 1;
- string ProfileNames = 2;
- string Active = 3;
-}
-
-message ProfileInfo {
- string Name = 1;
- bytes Content = 2;
-}
-
-message AnalysisMessage {
- string Name = 1;
- string Model = 2;
-}
-
-message Ack {
- string Status = 1;
-}
-
-message AckCheck {
- string Name = 1;
- string Status = 2;
- string Description = 3;
-}
-
-message ProfileLog {
- int64 Id = 1;
- string ProfileId = 2;
- string Timestamp = 3;
-}
-
-message CollectFlag {
- int64 Interval = 1;
- int64 Duration = 2;
- string Workload = 3;
- string OutputPath = 4;
- string Block = 5;
- string Network = 6;
- string Type = 7;
-}
-
-message TrainMessage {
- string DataPath = 1;
- string OutputPath = 2;
-}
-
-message DefineMessage {
- string WorkloadType = 1;
- string ProfileName = 2;
- bytes Content = 3;
-}
-
-message ScheduleMessage {
- string App = 1;
- string Type = 2;
- string Strategy = 3;
-}
diff --git a/atune.spec b/atune.spec
new file mode 100755
index 0000000..d9a2a8c
--- /dev/null
+++ b/atune.spec
@@ -0,0 +1,112 @@
+%define __global_requires_exclude_from /usr/libexec
+
+Summary: AI auto tuning system
+Name: atune
+Version: 0.2
+Release: 0.1
+License: Mulan PSL v1
+URL: https://gitee.com/openeuler/A-Tune
+Source: openeuler-A-Tune-v%{version}.tar.gz
+
+BuildRequires: rpm-build protobuf-compiler golang-bin python3-pytest procps-ng
+BuildRequires: sqlite >= 3.24.0
+Requires: systemd
+Requires: atune-client
+Requires: atune-db
+Requires: python3-dict2xml
+Requires: python3-flask-restful
+Requires: python3-pandas
+Requires: python3-scikit-optimize
+Requires: python3-xgboost
+Requires: prefetch_tuning
+Requires: perf
+Requires: sysstat
+Requires: hwloc-gui
+Requires: psmisc
+
+%define debug_package %{nil}
+
+%description
+atune is a service for atuned AI tuning system.
+
+%package client
+Summary: client tool for auto tuning system
+License: MuLan PSL v1
+
+%description client
+atune client tool for manage atuned AI tuning system.
+
+%package db
+Summary: database and AI model for auto tuning system
+License: MuLan PSL v1
+
+%description db
+Database and AI model used by atuned AI tuning system.
+
+%prep
+%setup -n A-Tune -q
+
+%build
+cd ../
+mkdir -p gopath/src/
+rm -rf gopath/src/%{name}
+mv A-Tune gopath/src/%{name}
+cd gopath/src/%{name}
+export GO111MODULE=off
+make
+cd ../
+cp -rf %{name} ../../A-Tune
+
+%install
+%make_install
+
+%check
+
+%files
+%license License/LICENSE
+%defattr(0640,root,root,-)
+%attr(0640,root,root) /usr/lib/atuned/modules/daemon_profile_server.so
+%attr(0640,root,root) %{_unitdir}/atuned.service
+%attr(0750,root,root) %{_bindir}/atuned
+%attr(0750,root,root) /usr/libexec/atuned/scripts/*
+%attr(0750,root,root) /usr/libexec/atuned/analysis/*
+%exclude /usr/libexec/atuned/analysis/models/
+%attr(0750,root,root) /usr/libexec/atuned/collector/*
+%attr(0750,root,root) %dir /usr/lib/atuned
+%attr(0750,root,root) %dir /usr/lib/atuned/modules
+%attr(0750,root,root) %dir /usr/libexec/atuned
+%attr(0750,root,root) %dir /usr/libexec/atuned/scripts
+%attr(0750,root,root) %dir /usr/libexec/atuned/analysis
+%attr(0750,root,root) %dir /usr/libexec/atuned/collector
+%attr(0750,root,root) %dir /usr/share/atuned
+%attr(0750,root,root) %dir /etc/atuned
+%attr(0750,root,root) /etc/atuned/*
+
+%files client
+%attr(0750,root,root) %{_bindir}/atune-adm
+%attr(0640,root,root) /usr/share/bash-completion/completions/atune-adm
+
+%files db
+%attr(0750,root,root) %dir /var/lib/atuned
+%attr(0750,root,root) %dir /var/run/atuned
+%attr(0750,root,root) /var/lib/atuned/atuned.db
+%attr(0750,root,root) %dir /usr/libexec/atuned
+%attr(0750,root,root) %dir /usr/libexec/atuned/analysis
+%attr(0750,root,root) %dir /usr/libexec/atuned/analysis/models
+%attr(0750,root,root) /usr/libexec/atuned/analysis/models/*
+
+%post
+%systemd_post atuned.service
+
+%preun
+%systemd_preun atuned.service
+
+%postun
+%systemd_postun_with_restart atuned.service
+
+%changelog
+* Thu Mar 19 2020 openEuler Buildteam - 0.2-0.1
+- Package init
+
+* Tue Nov 12 2019 openEuler Buildteam - 0.1-0.1
+- Package init
diff --git a/cmd/atune-adm/atune-adm.go b/cmd/atune-adm/atune-adm.go
deleted file mode 100644
index 79a9dcf..0000000
--- a/cmd/atune-adm/atune-adm.go
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package main
-
-import (
- "atune/common/config"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "os"
- "sort"
-
- "github.com/urfave/cli"
-)
-
-const (
- usageInfo = `atune-adm is a command line client for atuned AI tunning system`
-)
-
-func checkValid(ctx *cli.Context) error {
- return nil
-}
-
-func doBeforeJob(ctx *cli.Context) error {
- return nil
-}
-
-func main() {
- app := cli.NewApp()
- app.Name = "atune-adm"
- app.Usage = usageInfo
- app.Version = config.Version
-
- app.Flags = []cli.Flag{
- cli.StringFlag{
- Name: "address, a",
- Usage: "atuned address",
- Value: config.DefaultTgtAddr,
- },
- cli.StringFlag{
- Name: "port, p",
- Usage: "atuned port",
- Value: config.DefaultTgtPort,
- },
- }
-
- /*
- * for limitaion of cli, have to fix module load path
- */
-
- SVC.WalkServices(func(nm string, svc *SVC.ProfileService) error {
- ins, err := svc.NewInst(nil)
- if err != nil {
- return err
- }
- cmd, ok := ins.(cli.Command)
- if !ok {
- fmt.Printf("service %s doesn't implement cli.Command\n", nm)
- return fmt.Errorf("service %s doesn't implement cli.Command", nm)
- }
-
- app.Commands = append(app.Commands, cmd)
-
- return nil
- })
- sort.Sort(cli.CommandsByName(app.Commands))
- app.Before = doBeforeJob
- if err := app.Run(os.Args); err != nil {
- utils.Fatal(err)
- }
-}
diff --git a/cmd/atune-adm/buildins.go b/cmd/atune-adm/buildins.go
deleted file mode 100644
index 40d9fc5..0000000
--- a/cmd/atune-adm/buildins.go
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package main
-
-import (
- _ "atune/modules/client/profile"
-)
diff --git a/cmd/atuned/atuned.go b/cmd/atuned/atuned.go
deleted file mode 100644
index f27f01d..0000000
--- a/cmd/atuned/atuned.go
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package main
-
-import (
- "atune/common/config"
- "atune/common/log"
- "atune/common/registry"
- SVC "atune/common/service"
- "atune/common/sqlstore"
- "atune/common/utils"
- "fmt"
- "io/ioutil"
- "net"
- "os"
- "os/exec"
- "os/signal"
- "syscall"
-
- "github.com/coreos/go-systemd/daemon"
- "github.com/urfave/cli"
- "google.golang.org/grpc"
- "google.golang.org/grpc/reflection"
-)
-
-const (
- atunedUsage = `atuned daemon is the AI system daemon
-To get more info of how to use atuned:
- # atuned help
-`
-)
-
-type swServer struct {
- server *grpc.Server
- svcs map[string]interface{}
-}
-
-func newServer(rpc *grpc.Server) (*swServer, error) {
- server := new(swServer)
- server.server = rpc
- server.svcs = make(map[string]interface{})
-
- return server, nil
-}
-
-func createSvcInsts(ctx *cli.Context, svr *swServer) error {
- if err := SVC.WalkServices(func(nm string, svc *SVC.ProfileService) error {
- inst, err := svc.NewInst(ctx)
- if err != nil {
- fmt.Printf("Create %s instance failed\n", nm)
- return nil
- }
-
- log.Infof("Create %s service successfully\n", nm)
-
- sinst, ok := inst.(SVC.SvrService)
- if !ok {
- return fmt.Errorf("not impletment SvrService")
- }
-
- if err := sinst.RegisterServer(svr.server); err != nil {
- return err
- }
-
- svr.svcs[nm] = inst
-
- return nil
- }); err != nil {
- return err
- }
-
- return nil
-}
-
-func loadModules(ctx *cli.Context, svr *swServer, path string) error {
- exist, err := utils.PathExist(path)
- if err != nil {
- return err
- }
- if !exist {
- return nil
- }
-
- if err := utils.LoadPlugins(path); err != nil {
- return err
- }
-
- if err := createSvcInsts(ctx, svr); err != nil {
- return err
- }
-
- return nil
-}
-
-func checkValid(ctx *cli.Context) error {
- return nil
-}
-
-func doBeforeJob(ctx *cli.Context) error {
- if err := checkValid(ctx); err != nil {
- return err
- }
-
- // Load conf file
- cfg := config.NewCfg()
- if err := cfg.Load(); err != nil {
- log.Errorf("Faild to load config file, error: %v", err)
- return fmt.Errorf("Faild to load config file, error: %v", err)
- }
-
- store := &sqlstore.Sqlstore{
- Cfg: cfg,
- }
- // init the sqlite3 database engine
- if err := store.Init(); err != nil {
- log.Error(err)
- return err
- }
-
- services := registry.GetDaemonServices()
-
- for _, service := range services {
- log.Infof("initializing service: %s", service.Name)
- service.Instance.Set(cfg)
- if err := service.Instance.Init(); err != nil {
- return fmt.Errorf("service init faild: %v", err)
- }
- }
-
- // starting all service
- for _, srv := range services {
- service := srv
- backgroundService, ok := service.Instance.(registry.BackgroundService)
- if !ok {
- continue
- }
-
- go func() error {
- err := backgroundService.Run()
- if err != nil {
- log.Errorf("service %s running faild, reason: %v", service.Name, err)
- return err
- }
- return nil
- }()
- }
-
- return nil
-}
-
-func listenToSystemSignals(cmd *exec.Cmd) {
- signalChan := make(chan os.Signal, 1)
-
- signal.Notify(signalChan, os.Interrupt, os.Kill, syscall.SIGKILL)
- select {
- case <-signalChan:
- syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
- os.Exit(-1)
- }
-}
-
-func showlogo() {
- logo, err := ioutil.ReadFile("/usr/share/atuned/atune.logo")
- if err != nil {
- fmt.Print(err)
- }
-
- fmt.Print(string(logo))
-}
-
-func runatuned(ctx *cli.Context) error {
- if err := checkValid(ctx); err != nil {
- return err
- }
-
- lis, err := net.Listen("tcp", config.Address+":"+config.Port)
- if err != nil {
- log.Fatalf("failed to listen: %v", err)
- }
- s := grpc.NewServer()
-
- server, err := newServer(s)
- if err != nil {
- return err
- }
-
- if err := loadModules(ctx, server, config.DefaultModDaemonSvrPath); err != nil {
- return err
- }
-
- /* Show atuned Log*/
- showlogo()
- if err := utils.WaitForPyservice(); err != nil {
- log.Errorf("waiting for pyservice faild: %v", err)
- return err
- }
-
- log.Info("pyservice has been started")
- daemon.SdNotify(false, "READY=1")
-
- reflection.Register(s)
- if err := s.Serve(lis); err != nil {
- log.Fatalf("failed to serve: %v", err)
- }
-
- return nil
-}
-
-func main() {
- app := cli.NewApp()
- app.Name = "atuned"
- app.Usage = atunedUsage
-
- app.Version = config.Version
- app.Before = doBeforeJob
- app.Action = runatuned
-
- if err := app.Run(os.Args); err != nil {
- fmt.Printf("%s\n", err)
- os.Exit(1)
- }
-}
diff --git a/cmd/atuned/buildins.go b/cmd/atuned/buildins.go
deleted file mode 100644
index 965824c..0000000
--- a/cmd/atuned/buildins.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package main
-
-import (
- _ "atune/common/service/monitor"
- _ "atune/common/service/pyservice"
- _ "atune/common/service/timer"
-)
diff --git a/collection/README b/collection/README
deleted file mode 100644
index 21e6bb5..0000000
--- a/collection/README
+++ /dev/null
@@ -1,42 +0,0 @@
-Required Tools: perf mpstat vmstat iostat sar
-
-
-Usage:
-sh collect_raw_data.sh workload sample_time sample_interval out_log
-
-workload: the workload you want to tune
-sample_time: total collection time
-sample_interval: sample interval
-out_log: the output directory
-
-
-supported cpu: kunpeng 920,Hisilicon 1620
-
-
-supported metrics:
- hardware metrics:
- perf-cpu: IPC MPKI LLC ITLB DTLB Memory_Bound Store_Bound
- perf-memBW: MEM_Total CPU0 CPU1 CPU0_Die0 CPU0_Die1 CPU1_Die0 CPU1_Die1 MEM_CPU0_Die0_R MEM_CPU0_Die1_R MEM_CPU1_Die0_R MEM_CPU1_Die1_R MEM_CPU0_Die0_W MEM_CPU0_Die1_W MEM_CPU1_Die0_W MEM_CPU1_Die1_W
-
- cpu utilization:
- mpstat: %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
-
- system:
- vmstat: procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
- r b swpd free buff cache si so bi bo in cs us sy id wa st
- sar-load:runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked
- sar-task:proc/s cswch/s
- sysctl:"/proc/sys/kernel/threads-max","/proc/sys/fs/file-nr","/proc/loadavg"
-
- disk:
- iostat: r/s w/s rMB/s wMB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util
-
- network:
- sar-network: rxpck/s txpck/s rxkB/s txkB/s rxcmp/s txcmp/s rxmcst/s %ifutil
- sar-net_err: rxerr/s txerr/s coll/s rxdrop/s txdrop/s txcarr/s rxfram/s rxfifo/s txfifo/s
-
- memory:
- sar-paging: pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff
- /proc/meminfo:
- "MemTotal","MemFree","MemAvailable","Buffers","Cached","SwapCached","Active","Inactive","Active(anon)","Inactive(anon)","Active(file)","Inactive(file)","Unevictable","Mlocked","SwapTotal","SwapFree","Dirty","Writeback","AnonPages","Mapped","Shmem","Slab","SReclaimable","SUnreclaim","KernelStack","PageTables","NFS_Unstable","Bounce","WritebackTmp","CommitLimit","Committed_AS","VmallocTotal","VmallocUsed","VmallocChunk","Percpu","HardwareCorrupted","AnonHugePages","ShmemHugePages","ShmemPmdMapped","CmaTotal","CmaFree","HugePages_Total","HugePages_Free","HugePages_Rsvd","HugePages_Surp","Hugepagesize","Hugetlb"
-
diff --git a/collection/collect_raw_data.sh b/collection/collect_raw_data.sh
deleted file mode 100644
index ea50d76..0000000
--- a/collection/collect_raw_data.sh
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/bin/bash
-
-if [ ! $# == 4 ]; then
- echo "Usage: collect_raw_data.sh workload sample_time sample_interval out_log"
- exit
-fi
-
-DIR=$(dirname $0)
-
-bench=$1
-sample_time=$2
-interval=$3
-out_log=$4
-tag=$(date +%Y%m%d-%H%M%S)
-
-pids=$(pidof mpstat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof vmstat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof iostat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof perf)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof sar)
-for pid in $pids
-do
- kill -15 $pid
-done
-
-killall get_meminfo.sh 2>/dev/null
-killall get_sysctl.sh 2>/dev/null
-
-mkdir -p $out_log
-
-#echo 3 > /proc/sys/vm/drop_caches
-echo "start collect raw data"
-
-LC_TIME="POSIX" mpstat -P ALL ${interval} > ${out_log}/${bench}-mpstat-${tag}.log &
-LC_TIME="POSIX" sar -w ${interval} > ${out_log}/${bench}-sar-task-${tag}.log &
-LC_TIME="POSIX" sar -q ${interval} > ${out_log}/${bench}-sar-load-${tag}.log &
-LC_TIME="POSIX" sar -B ${interval} > ${out_log}/${bench}-sar-paging-${tag}.log &
-LC_TIME="POSIX" sar -n EDEV ${interval} > ${out_log}/${bench}-sar-net_err-${tag}.log &
-LC_TIME="POSIX" sar -n DEV ${interval} > ${out_log}/${bench}-sar-network-${tag}.log &
-vmstat -n ${interval} > ${out_log}/${bench}-vmstat-${tag}.log &
-iostat -x -m -d ${interval} > ${out_log}/${bench}-iostat-${tag}.log &
-stdbuf -oL sh $DIR/perf-cpu.sh ${interval} > ${out_log}/${bench}-perf-cpu-${tag}.log &
-stdbuf -oL sh $DIR/perf-memBW.sh ${interval} > ${out_log}/${bench}-perf-memBW-${tag}.log &
-$DIR/get_meminfo.sh ${interval} > ${out_log}/${bench}-meminfo-${tag}.log &
-$DIR/get_sysctl.sh ${interval} > ${out_log}/${bench}-sysctl-${tag}.log &
-
-
-#collection time
-sleep ${sample_time}
-
-
-pids=$(pidof mpstat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof vmstat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof iostat)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof perf)
-for pid in $pids
-do
- kill -15 $pid
-done
-pids=$(pidof sar)
-for pid in $pids
-do
- kill -15 $pid
-done
-
-killall get_meminfo.sh
-killall get_sysctl.sh
diff --git a/collection/collect_training_data.sh b/collection/collect_training_data.sh
deleted file mode 100644
index c7dbb60..0000000
--- a/collection/collect_training_data.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-
-if [ ! $# == 7 ]; then
- echo "Usage: collect_training_data.sh workload sample_time sample_interval out block_dev net_dev workload_type"
- exit
-fi
-
-
-workload=$1
-sample_time=$2
-interval=$3
-out=$4
-block_dev=$5
-net_dev=$6
-workload_type=$7
-tag=$(date +%Y%m%d-%H%M%S)
-
-DIR=$(dirname $0)
-out_log=/tmp/atune/${workload}-${tag}
-
-sh $DIR/collect_raw_data.sh ${workload} ${sample_time} ${interval} ${out_log}
-
-echo "start generate training data"
-python3 $DIR/parse_data.py ${out_log} ${out} -b ${block_dev} -n ${net_dev} -w ${workload_type}
diff --git a/collection/get_meminfo.sh b/collection/get_meminfo.sh
deleted file mode 100755
index 8c30a55..0000000
--- a/collection/get_meminfo.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/sh
-
-if [ $# -lt 1 ]
-then
- echo "Usage: `basename $0` interval"
- exit 1
-fi
-
-interval=$1
-tag=$(date +%Y%m%d-%H%M%S)
-
-awk -F':' '{printf "\"%s\",", $1}' /proc/meminfo
-echo ""
-while :
-do
- awk '{printf "%s,", $2}' /proc/meminfo
- echo ""
- sleep ${interval}
-done
diff --git a/collection/get_sysctl.sh b/collection/get_sysctl.sh
deleted file mode 100755
index 193817d..0000000
--- a/collection/get_sysctl.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-
-if [ $# -lt 1 ]
-then
- echo "Usage: `basename $0` interval"
- exit 1
-fi
-
-interval=$1
-
-files=(/proc/sys/kernel/threads-max /proc/sys/fs/file-nr /proc/loadavg)
-
-for file in ${files[@]}
-do
- echo -n \"${file}\",
-done
-echo ""
-
-while :
-do
- for file in ${files[@]}
- do
- echo -n \"`cat ${file}`\",
- done
- echo ""
- sleep ${interval}
-done
diff --git a/collection/parse_data.py b/collection/parse_data.py
deleted file mode 100644
index 594a847..0000000
--- a/collection/parse_data.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Parse data and generate csv.
-"""
-
-from __future__ import print_function
-import os
-import re
-import csv
-from itertools import chain
-
-from parser import load_parser
-
-def parse_data(parser_confs, yield_data_name=True, early_stop=False):
- """parse-data generator
-
- @param parser_confs: A list which contains the configuretion of parsers. For example,
- [{"name": "mpstat", "data_to_collect": ["%usr", "%sys"],
- "dev_list": ["all"]},
- {"name": "iostat", "data_to_collect": ["rMB/s", "r_await", "%util"],
- "dev_list": ["sdb"]},
- ...]
- @param yield_data_name: Whether or not yield the name of fields. If yield_data_name is True,
- then the first yield data is the names of fields
- @param early_stop: If early_stop is True and one of parsers raises StopIteration,
- then it will raise StopIteration.
- Otherwise, it will raise StopIteration util all parsers raise StopIteration,
- and None will fill in suitable position if some parsers raise StopIteration
- before that.
- @return: A generator of which `next` function will return a list contains data
- or the name of data
- """
- parsers = [load_parser(pf["name"])(**pf) for pf in parser_confs]
- if yield_data_name:
- yield list(chain.from_iterable([p.get_data_name() for p in parsers]))
-
- while True:
- data = []
- for parser in parsers:
- # fill with None if data in a parser is less than others
- try:
- data.extend(parser.get_next_data())
- except StopIteration:
- if early_stop:
- return
- data.extend([None] * parser.get_data_num())
- # if all data is None, then stop
- if all(d is None for d in data):
- return
- yield data
-
-
-def generate_csv(input_dir, output_dir, block_dev, net_dev, workload):
- parse_conf = {
- 'early_stop': True,
- 'yield_data_name': False,
- 'parser_confs':
- [
- {
- 'name': 'mpstat',
- 'raw_data_file': '',
- 'data_to_collect': ['%usr', '%sys', '%iowait', '%irq', '%guest'],
- 'dev_list': 'all',
- 'alias': 'cpu'
- }, {
- 'name': 'iostat',
- 'raw_data_file': '',
- 'data_to_collect': ['rMB/s', 'wMB/s', '%util'],
- 'dev_list': [],
- 'skip_first': True,
- 'alias': 'io',
- }, {
- 'name': 'sar-with-dev',
- 'raw_data_file': '',
- 'data_to_collect': ['rxkB/s', 'txkB/s', 'rxpck/s', 'txpck/s', '%ifutil'],
- 'dev_list': [],
- 'skip_first': True,
- 'alias': 'sar-network'
- }, {
- 'name': 'perf',
- 'raw_data_file': '',
- 'data_to_collect': ['IPC', 'MPKI', "LLC", "ITLB", "DTLB"],
- 'interval': 1,
- 'alias': 'perf-cpu',
- }, {
- 'name': 'perf',
- 'raw_data_file': '',
- 'data_to_collect': ['MEM_Total'],
- 'interval': 5,
- 'alias': 'perf-memBW',
- }
- ]
- }
- raw_data_logs = os.listdir(input_dir)
- pattern = re.compile(r"(.*)-(mpstat|iostat|vmstat|meminfo|perf-cpu|perf-memBW|sar-network)-(\d{8}-\d{6}).log")
- matches = [pattern.match(p) for p in raw_data_logs]
- path_map = {}
- for match in matches:
- if not match:
- continue
- if match.group(1) not in path_map:
- path_map[match.group(1)] = {}
- if match.group(3) not in path_map[match.group(1)]:
- path_map[match.group(1)][match.group(3)] = {}
- path_map[match.group(1)][match.group(3)][match.group(2)] = os.path.join(input_dir, match.group(0))
-
- if not os.path.exists(output_dir):
- os.makedirs(output_dir)
-
- for benchmark, vb in path_map.items():
- for tag, paths in vb.items():
- parse_conf["yield_data_name"] = False
- parse_conf["early_stop"] = True
- for parser_conf in parse_conf["parser_confs"]:
- if parser_conf["name"] in ("perf", "sar-with-dev"):
- parser_conf["raw_data_file"] = paths[parser_conf["alias"]]
- else:
- parser_conf["raw_data_file"] = paths[parser_conf["name"]]
- if parser_conf["name"] == "iostat":
- parser_conf["dev_list"] = [block_dev]
- if parser_conf["alias"] in ("sar-network", "sar-net_err"):
- parser_conf["dev_list"] = [net_dev]
-
- csv_path = os.path.join(output_dir, "{}-{}.csv".format(benchmark, tag))
- with open(csv_path, 'w') as fd:
- csv_writer = csv.writer(fd)
- for result in parse_data(**parse_conf):
- result.append(workload)
- csv_writer.writerow(result)
- print("generate {} successfully".format(csv_path))
-
-
-if __name__ == "__main__":
- import argparse
-
- arg_parser = argparse.ArgumentParser(description="parser output of mpstat, iostat, nicstat ...",
- formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=80))
- arg_parser.add_argument('input', metavar='input',
- help='input dir')
- arg_parser.add_argument('output', metavar='output',
- help='output dir')
- arg_parser.add_argument('-b', '--block', metavar='DEV', default='sda', help='block device')
- arg_parser.add_argument('-n', '--net', metavar='DEV', default='eth0', help='net device')
- arg_parser.add_argument('-w', '--workload', metavar='WORKLOAD', default='idle', help='workload type')
-
- args = arg_parser.parse_args()
- generate_csv(args.input, args.output, args.block, args.net, args.workload)
diff --git a/collection/parser/__init__.py b/collection/parser/__init__.py
deleted file mode 100644
index edce213..0000000
--- a/collection/parser/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Init file.
-"""
-
-from .loader import load_parser
diff --git a/collection/parser/base.py b/collection/parser/base.py
deleted file mode 100644
index 341670b..0000000
--- a/collection/parser/base.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Abstract class of all parsers.
-"""
-
-import os
-import abc
-
-
-class Parser(object):
- """Abstract class of all parsers"""
-
- __metaclass__ = abc.ABCMeta
-
- def __init__(self, raw_data_file, data_to_collect, **kwargs):
- """Initialize a parser
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param alias: alias name of output fields
- """
- self._raw_data_file = raw_data_file
- if not os.path.exists(self._raw_data_file):
- return
- self._data_to_collect = data_to_collect
- self._iter = None
- self._check_data_to_collect()
- self._prefix = kwargs.get("alias", self.__class__.__name__.lower().replace("parser", ""))
-
- def __iter__(self):
- """Get the iteration of the parser
-
- @return: the iteration of the parser
- """
- if not self._iter:
- self._iter = self._get_iter()
- return self._iter
-
- @abc.abstractmethod
- def _check_data_to_collect(self):
- """Interface to check data_to_collect. If any metrics in data_to_collect
- is not supported, it will raise ValueError
- """
-
- @abc.abstractmethod
- def _get_iter(self):
- """Interface to get the iteration of the parser.
-
- @return: the iteration of the parser
- """
-
- def get_data_name(self):
- """Get the names of all data fields.
-
- @return: a list of string which represents the name of all data fields
- """
- if not os.path.exists(self._raw_data_file):
- return []
- if hasattr(self, "_dev_list"):
- return ["{prefix}.{dev}.{attr}".format(prefix=self._prefix, dev=dev, attr=attr)
- for dev in getattr(self, "_dev_list")
- for attr in self._data_to_collect]
- return ["{prefix}.{attr}".format(prefix=self._prefix, attr=attr)
- for attr in self._data_to_collect]
-
- def get_data_num(self):
- """Get the number of a batch of data
-
- @return: the number of data
- """
- if not os.path.exists(self._raw_data_file):
- return 0
- num = len(self._data_to_collect)
- if hasattr(self, "_dev_list"):
- num *= len(getattr(self, "_dev_list"))
- return num
-
- def get_next_data(self):
- """Get the next batch of data
-
- @return: a list of data
- """
- if not os.path.exists(self._raw_data_file):
- return []
- if not self._iter:
- self._iter = self._get_iter()
- return next(self._iter)
diff --git a/collection/parser/iostat_parser.py b/collection/parser/iostat_parser.py
deleted file mode 100644
index f142038..0000000
--- a/collection/parser/iostat_parser.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The parser to parse the output of iostat.
-"""
-
-from __future__ import print_function
-
-from . import base
-
-
-class IostatParser(base.Parser):
- """The parser to parse the output of iostat"""
-
- def __init__(self, raw_data_file, data_to_collect, skip_first=True, **kwargs):
- """Initialize a iostat parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param dev_list: list of devices of which metrics whille be collectted
- @param skip_first: skip the first batch of data or not. Bacause the first
- output of iostat is the statistics information since
- boot, we can skip it.
- @param alias: alias name of output fields (default: "iostat")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- self._dev_list = kwargs.get("dev_list", None)
- self._check_dev()
-
- # the first output of iostat is the statistics information since boot, so we can skip it
- if skip_first:
- self.get_next_data()
-
- def _check_data_to_collect(self):
- """Read the first batch output of iostat and check whether or not all
- metrics in data_to_collect are in the output. If not, it will raise
- ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- # skip the first line
- raw_data_fd.readline()
- for line in raw_data_fd:
- line = line.strip()
- if line:
- datas = line.split()[1:]
- break
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _check_dev(self):
- """Read the first batch output of iostat and check whether or not all
- devices in dev_list are in the output. If not, it will raise ValueError.
- """
- if not self._dev_list:
- raise ValueError("You must assigned at least one device")
-
- devs = set()
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- for line in raw_data_fd:
- if line.strip():
- break
- for line in raw_data_fd:
- if not line.strip():
- break
- devs.add(line.split()[0])
-
- diff_set = set(self._dev_list) - devs
- if diff_set:
- raise ValueError("Can not find block device `{}`".format(','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the iostat parser.
-
- @return: the iteration of the iostat parser
- """
- # status: 0: ok, we have read data successfully
- # 1: we need to read more data
- status = 0
- header = False
- data = {}
- attrs = []
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- for row_num, line in enumerate(raw_data_fd, 2):
- line = line.strip()
- if not line:
- if status:
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
- data.clear()
- status = 0
- header = True
- continue
- status = 1
- line_part = line.split()
- if header:
- attrs = line_part[1:]
- header = False
- else:
- if len(attrs) != len(line_part) - 1:
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- return
- dev = line_part[0]
- data[dev] = dict(zip(attrs, [float(d) for d in line_part[1:]]))
diff --git a/collection/parser/loader.py b/collection/parser/loader.py
deleted file mode 100644
index 2f8e1f5..0000000
--- a/collection/parser/loader.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Load a parser from its name.
-"""
-
-import parser.base
-
-_NAMESPASE = "parser"
-_PREFIX = ""
-_SUFFIX = "_parser"
-_INTERFACE = parser.base.Parser
-
-def load_parser(parser_name):
- """load a parser from its name.
-
- @param parser_name: the name of the parser to load
- @return: class of the parser to load
- """
- module_name = "{}.{}{}{}".format(_NAMESPASE, _PREFIX, parser_name.replace("-", "_"), _SUFFIX)
- module = __import__(module_name)
- path = module_name.split(".")
- path.pop(0)
-
- while path:
- module = getattr(module, path.pop(0))
-
- for name in dir(module):
- cls = getattr(module, name)
- if issubclass(cls, _INTERFACE):
- return cls
-
- return ImportError("Can not find the parser class")
diff --git a/collection/parser/meminfo_parser.py b/collection/parser/meminfo_parser.py
deleted file mode 100644
index 53e9c16..0000000
--- a/collection/parser/meminfo_parser.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The parser to parse the output of get_meminfo.sh.
-"""
-
-import csv
-
-from . import base
-
-
-class MeminfoParser(base.Parser):
- """The parser to parse the output of get_meminfo.sh"""
-
- def __init__(self, raw_data_file, data_to_collect, **kwargs):
- """Initialize a meminfo parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param alias: alias name of output fields (default: "meminfo")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- def _check_data_to_collect(self):
- """Read the first batch output of get_meminfo.sh and check whether or
- not all metrics in data_to_collect are in the output. If not, it will
- raise ValueError.
- """
- with open(self._raw_data_file) as csv_fd:
- reader = csv.reader(csv_fd)
- header = next(reader)
- header.append("HugePages")
- header.append("MemUsed")
- diff_set = set(self._data_to_collect) - set(header)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the iostat parser.
-
- @return: the iteration of the iostat parser
- """
- with open(self._raw_data_file) as csv_fd:
- reader = csv.DictReader(csv_fd, quoting=csv.QUOTE_NONNUMERIC)
- for row in reader:
- data = []
- for data_name in self._data_to_collect:
- if data_name == "HugePages":
- data.append(row["HugePages_Total"] - row["HugePages_Free"])
- elif data_name == "MemUsed":
- data.append(row["MemTotal"] - row["MemFree"] - row["Hugepagesize"] * row["HugePages_Free"])
- else:
- data.append(row[data_name])
- yield data
diff --git a/collection/parser/mpstat_parser.py b/collection/parser/mpstat_parser.py
deleted file mode 100644
index 613e697..0000000
--- a/collection/parser/mpstat_parser.py
+++ /dev/null
@@ -1,160 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Parse the string of CPUs to a list of CPUs.
-"""
-
-from __future__ import print_function
-
-import re
-
-from . import base
-
-_CPU_PATTERNS = {"single": re.compile(r"^\s*(\d+)\s*$"),
- "range": re.compile(r"^\s*(\d+)\s*-\s*(\d+)\s*$"),
- "exclude": re.compile(r"^\s*\^(\d+)\s*$")}
-
-
-def _parse_cpu_str(cpu_str):
- """Parse the string of CPUs to a list of CPUs.
-
- @param cpu_str: the string of CPUs to parse
- @return: a list of string which represents CPU.
- """
- matches = [{key: pattern.match(sub_list) for key, pattern in _CPU_PATTERNS.items()}
- for sub_list in cpu_str.split(',')]
-
- includes = set()
- excludes = set()
- for match in matches:
- if match['single'] is not None:
- includes.add(int(match['single'].group(1)))
- elif match['range'] is not None:
- # in "start-end" format, both `start` and `end` are included
- includes.update(range(int(match['range'].group(1)), int(match['range'].group(2)) + 1))
- elif match['exclude'] is not None:
- excludes.add(int(match['exclude'].group(1)))
- else:
- raise ValueError("Unknown cpu str format `{}`".format(cpu_str))
-
- cpu_list = list(includes - excludes)
- cpu_list.sort()
- return map(str, cpu_list)
-
-
-def _get_available_cpus():
- """Get the avaiable CPUs.
-
- @return: a list of string which represents CPU.
- """
- with open('/sys/devices/system/cpu/possible', 'r') as possible_fd:
- possible = possible_fd.read()
- return _parse_cpu_str(possible)
-
-
-class MpstatParser(base.Parser):
- """The parser to parse the output of mpstat"""
-
- def __init__(self, raw_data_file, data_to_collect, **kwargs):
- """Initialize a mpstat parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param dev_list: list of devices of which metrics whille be collectted
- @param alias: alias name of output fields (default: "mpstat")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- self._dev_list = kwargs.get("dev_list", None)
- if self._dev_list == "all":
- self._dev_list = ["all"]
- elif self._dev_list == "ALL":
- self._dev_list = ["all"]
- self._dev_list.extend(_get_available_cpus())
- else:
- self._dev_list = _parse_cpu_str(self._dev_list)
- self._check_dev()
-
- def _check_data_to_collect(self):
- """Read the first batch output of mpstat and check whether or not all
- metrics in data_to_collect are in the output. If not, it will raise
- ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- raw_data_fd.readline()
- line_part = raw_data_fd.readline().split()
- cpu_idx = line_part.index("CPU")
- datas = line_part[cpu_idx + 1:]
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _check_dev(self):
- """Read the first batch output of mpstat and check whether or not all
- devices in dev_list are in the output. If not, it will raise ValueError.
- """
- if not self._dev_list:
- raise ValueError("You must assigned at least one device")
-
- devs = set()
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- raw_data_fd.readline()
- cpu_idx = raw_data_fd.readline().split().index("CPU")
- for line in raw_data_fd:
- if not line.strip():
- continue
- dev = line.split()[cpu_idx]
- if dev in devs:
- break
- else:
- devs.add(dev)
- if "CPU" in devs:
- devs.remove("CPU")
-
- diff_set = set(self._dev_list) - devs
- if diff_set:
- raise ValueError("Can not find block device `{}`".format(','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the mpstat parser.
-
- @return: the iteration of the mpstat parser
- """
- data = {}
- attrs = []
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- for row_num, line in enumerate(raw_data_fd, 2):
- if not line.strip():
- continue
- line_part = line.split()
- if "CPU" in line_part:
- cpu_idx = line_part.index("CPU")
- attrs = line_part[cpu_idx + 1:]
- else:
- if len(attrs) != len(line_part) - cpu_idx - 1:
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- return
- line_data = [float(d) for d in line_part[cpu_idx + 1:]]
- if line_part[cpu_idx] not in data:
- data[line_part[cpu_idx]] = dict(zip(attrs, line_data))
- else:
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
- data = {}
- data[line_part[cpu_idx]] = dict(zip(attrs, line_data))
- if all(dev in data for dev in self._dev_list):
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
diff --git a/collection/parser/nicstat_parser.py b/collection/parser/nicstat_parser.py
deleted file mode 100644
index adffb0e..0000000
--- a/collection/parser/nicstat_parser.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The parser to parse the output of nicstat.
-"""
-
-from __future__ import print_function
-
-from . import base
-
-class NicstatParser(base.Parser):
-
- """The parser to parse the output of nicstat"""
-
- def __init__(self, raw_data_file, data_to_collect, skip_first=True, **kwargs):
- """Initialize a nicstat parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param dev_list: list of devices of which metrics whille be collectted
- @param skip_first: skip the first batch of data or not. Bacause the first
- output of nicstat is the statistics information since
- boot, we can skip it.
- @param alias: alias name of output fields (default: "nicstat")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- self._dev_list = kwargs.get("dev_list", None)
- self._check_dev()
-
- # the first output of nicstat is the statistics information since boot, so we can skip it
- if skip_first:
- self.get_next_data()
-
- def _check_data_to_collect(self):
- """Read the first batch output of nicstat and check whether or not all
- metrics in data_to_collect are in the output. If not, it will raise
- ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- line = raw_data_fd.readline()
- datas = line.split()[2:]
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _check_dev(self):
- """Read the first batch output of nicstat and check whether or not all
- devices in dev_list are in the output. If not, it will raise ValueError.
- """
- if not self._dev_list:
- raise ValueError("You must assigned at least one device")
-
- devs = set()
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- for line in raw_data_fd:
- line_part = line.split()
- if line_part[0] == "Time":
- break
- else:
- devs.add(line_part[1])
- diff_set = set(self._dev_list) - devs
- if diff_set:
- raise ValueError("Can not find nic device `{}`".format(','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the mpstat parser.
-
- @return: the iteration of the mpstat parser
- """
- data = {}
- attrs = []
- first_line = True
- with open(self._raw_data_file, 'r') as raw_data_fd:
- for row_num, line in enumerate(raw_data_fd, 1):
- line_part = line.strip().split()
- if line_part[0] == "Time":
- if first_line:
- first_line = False
- else:
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
- attrs = line_part[2:]
- data.clear()
- else:
- if len(attrs) != len(line_part) - 2:
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- return
- data[line_part[1]] = dict(zip(attrs, [float(d) for d in line_part[2:]]))
- if data:
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
diff --git a/collection/parser/perf_parser.py b/collection/parser/perf_parser.py
deleted file mode 100644
index bd51d6d..0000000
--- a/collection/parser/perf_parser.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-The parser to parse the output of perf-cpu.sh and perf-mem.sh.
-"""
-
-from __future__ import division
-from __future__ import print_function
-from . import base
-
-
-class PerfParser(base.Parser):
- """The parser to parse the output of perf-cpu.sh and perf-mem.sh"""
-
- def __init__(self, raw_data_file, data_to_collect, interval=1, **kwargs):
- """Initialize a perf parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param interval: the interval time of data. It is only for perf-mem.sh.
- If you want to parse the output of perf-cpu.sh, please
- set interval to 1.
- @param alias: alias name of output fields (default: "perf")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- self._interval = interval
-
- def _check_data_to_collect(self):
- """Read the first batch output of perf-cpu.sh or perf-mem.sh and check
- whether or not all metrics in data_to_collect are in the output. If
- not, it will raise ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- datas = raw_data_fd.readline().split()
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the perf parser.
-
- @return: the iteration of the perf parser
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- attrs = raw_data_fd.readline().split()
- for row_num, line in enumerate(raw_data_fd, 3):
- line_part = line.split()
- line_data = [float(d[:-1] if d.endswith('%') else d) / self._interval for d in line_part]
- if len(attrs) != len(line_data):
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- return
- data = dict(zip(attrs, line_data))
- yield [data[attr] for attr in self._data_to_collect]
diff --git a/collection/parser/sar_with_dev_parser.py b/collection/parser/sar_with_dev_parser.py
deleted file mode 100644
index 2927054..0000000
--- a/collection/parser/sar_with_dev_parser.py
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Sar parser with device.
-"""
-
-from __future__ import print_function
-
-from . import base
-
-
-class SarWithDevParser(base.Parser):
- """Docstring for SarWithDevParser. """
-
- def __init__(self, raw_data_file, data_to_collect, **kwargs):
- """Initialize a sar parser with device. The device field must be the second column.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param dev_list: list of devices of which metrics whille be collectted
- @param alias: alias name of output fields (default: "sarwithdev")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
- self._dev_list = kwargs.get("dev_list", None)
-
- def _check_data_to_collect(self):
- """Read the first batch output of sar and check whether or not all
- metrics in data_to_collect are in the output. If not, it will raise
- ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- raw_data_fd.readline()
- line_part = raw_data_fd.readline().split()
- datas = line_part[2:]
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _check_dev(self):
- """Read the first batch output of sar and check whether or not all
- devices in dev_list are in the output. If not, it will raise ValueError.
- """
- if not self._dev_list:
- raise ValueError("You must assigned at least one device")
-
- devs = set()
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- raw_data_fd.readline()
-
- dev_field_name = raw_data_fd.readline().split()[1]
- for line in raw_data_fd:
- if not line.split():
- continue
- dev = line.split()[1]
- if dev == dev_field_name:
- break
- devs.add(dev)
- diff_set = set(self._dev_list) - devs
- if diff_set:
- raise ValueError("Can not find device `{}` in file `{}`".format(','.join(diff_set), self._raw_data_file))
-
- def _get_iter(self):
- """Get the iteration of the sar parser.
-
- @return: the iteration of the sar parser
- """
- data = {}
- attrs = []
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- for row_num, line in enumerate(raw_data_fd, 2):
- if line.strip():
- line_part = line.split()
- dev_field_name = line_part[1]
- attrs = line_part[2:]
- break
- for row_num, line in enumerate(raw_data_fd, row_num):
- if not line.strip():
- continue
- line_part = line.split()
- if dev_field_name in line_part:
- attrs = line_part[2:]
- else:
- if len(attrs) != len(line_part) - 2:
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- line_data = [float(d) for d in line_part[2:]]
- if line_part[1] not in data:
- data[line_part[1]] = dict(zip(attrs, line_data))
- else:
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
- data = {}
- data[line_part[1]] = dict(zip(attrs, line_data))
- if all(dev in data for dev in self._dev_list):
- yield [data[dev][attr] for dev in self._dev_list for attr in self._data_to_collect]
diff --git a/collection/parser/vmstat_parser.py b/collection/parser/vmstat_parser.py
deleted file mode 100644
index 96ed598..0000000
--- a/collection/parser/vmstat_parser.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Vmstat parser.
-"""
-
-from __future__ import print_function
-
-from . import base
-
-
-class VmstatParser(base.Parser):
- """Docstring for VmstatParser. """
-
- def __init__(self, raw_data_file, data_to_collect, skip_first=True, **kwargs):
- """Initialize a vmstat parser.
-
- @param raw_data_file: the path of raw data
- @param data_to_collect: list of str which represents the metrics to parse
- @param skip_first: skip the first batch of data or not. Bacause the first
- output of vmstat is the statistics information since
- boot, we can skip it.
- @param alias: alias name of output fields (default: "iostat")
- """
- base.Parser.__init__(self, raw_data_file, data_to_collect, **kwargs)
-
- # the first output of vmstat is the statistics information since boot, so we can skip it
- if skip_first:
- self.get_next_data()
-
- def _check_data_to_collect(self):
- """Read the first batch output of vmstat and check whether or not all
- metrics in data_to_collect are in the output. If not, it will raise
- ValueError.
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- datas = raw_data_fd.readline().split()
- diff_set = set(self._data_to_collect) - set(datas)
- if diff_set:
- raise ValueError("`{}`: Unknown data name `{}`".format(self._raw_data_file, ','.join(diff_set)))
-
- def _get_iter(self):
- """Get the iteration of the vmstat parser.
-
- @return: the iteration of the vmstat parser
- """
- with open(self._raw_data_file, 'r') as raw_data_fd:
- raw_data_fd.readline()
- attrs = raw_data_fd.readline().split()
- for row_num, line in enumerate(raw_data_fd, 3):
- line_part = line.split()
- line_data = [int(d) for d in line_part]
- if len(attrs) != len(line_data):
- print("WARNING: {}: Line {}: The number of columns may be wrong."
- .format(self._raw_data_file, row_num))
- return
- data = dict(zip(attrs, line_data))
- yield [data[attr] for attr in self._data_to_collect]
diff --git a/collection/perf-cpu.sh b/collection/perf-cpu.sh
deleted file mode 100644
index 0722e01..0000000
--- a/collection/perf-cpu.sh
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/bin/bash
-
-function perf_cpu () {
-
- if dmidecode -t processor | grep -q -E 'Kunpeng|Hisilicon' ; then
- L1DCA='r0004'
- L1DCM='r0003'
- L1ICA='r0014'
- L1ICM='r0001'
-
- L2DCA='r0016'
- L2DCM='r0017'
- L2ICA='r0027'
- L2ICM='r0028'
-
- LLCA='r0032'
- LLCM='r0033'
-
- ITLBA='r0002'
- ITLBM='r0026'
-
- DTLBA='r0005'
- DTLBM='r0025'
-
- Cycles='r0011'
- RetiredInsts='r0008'
-
- MemStallLoad='r7004'
- MemStallStore='r7005'
- FetchBubbles='r2014'
- DecodedInsts='r001b'
- MemStallL2Miss='r7007'
-
- StallBackend='r0024'
-
- #Events="-e $LLCA,$LLCM,$ITLBA,$ITLBM,$DTLBA,$DTLBM,$Cycles,$RetiredInsts,$MemStallLoad,$MemStallStore,$FetchBubbles,$DecodedInsts,$MemStallL2Miss"
-
- Events="-e $LLCA,$LLCM,$ITLBA,$ITLBM,$DTLBA,$DTLBM,$Cycles,$RetiredInsts,$StallBackend,$MemStallLoad,$MemStallStore"
-
-
-
-
- else
- echo "can not support cpu architecture..."
- exit
- fi
-
- let interval=$interval*1000
-
- timeout $ts perf stat -x ',' -a -I $interval $Events 2>&1 | \
- awk -F, '
- BEGIN {
- tpre=-1;
- first=1;
- pcount=0;
- }
- {
- tcurr=$1;
-
- if(first==1) {
- tpre=tcurr;
- first=0;
- printf("#######################################################Perf Info##############################################################################\n");
- #printf(" IPC LLC MPKI ITLB DTLB Frount-End Bad-Speculation Retiring Back-End Memory_Bound DRAM Store\n");
- printf(" IPC MPKI LLC ITLB DTLB StallBackend/Insts StallBackend/cycles Memory_Bound Store_Bound\n");
- }
-
- if(tcurr != tpre)
- {
- #printf("%1.3f %10.2f%% %10.2f %10.2f%% %10.2f%% %10.2f%% %10.2f%% %10.2f%% %10.2f%% %10.2f%% %10.2f%% %10.2f%%\n",insts/cycles,llcmiss/llcref*100,llcmiss/insts*1000, itlbmiss/itlbref*100,dtlbmiss/dtlbref*100,fetchbubbles/(4*cycles)*100,(decodedinsts-insts)/(4*cycles)*100,insts/(4*cycles)*100, (1-fetchbubbles/(4*cycles)-(decodedinsts-insts)/(4*cycles)-insts/(4*cycles))*100, (memstallload+memstallstore)/cycles*100, memstalll2miss/cycles*100, memstallstore/cycles*100);
- printf("%1.3f %10.2f %10.2f%% %10.2f%% %10.2f%% %10.2f %10.2f %10.2f%% %10.2f%%\n",insts/cycles,llcmiss/insts*1000,llcmiss/llcref*100,itlbmiss/itlbref*100,dtlbmiss/dtlbref*100,stallbackend/insts, stallbackend/cycles, (memstallload+memstallstore)/cycles*100,memstallstore/cycles*100);
-
- tpre=tcurr;
- pcount++;
- }
-
- switch ($4)
- {
- case "r0032":
- llcref=$2;
- break;
- case "r0033":
- llcmiss=$2;
- break;
-
- case "r0026":
- itlbref=$2;
- break;
- case "r0002":
- itlbmiss=$2;
- break;
-
- case "r0025":
- dtlbref=$2;
- break;
- case "r0005":
- dtlbmiss=$2;
- break;
-
- case "r0011":
- cycles=$2;
- break;
- case "r0008":
- insts=$2;
- break;
- case "r7004":
- memstallload=$2;
- break;
- case "r7005":
- memstallstore=$2;
- break;
- case "r2014":
- fetchbubbles=$2;
- break;
- case "r001b":
- decodedinsts=$2;
- break;
- case "r7007":
- memstalll2miss=$2;
- break;
- case "r0024":
- stallbackend=$2;
- break;
- }
-
-
- }
- '
-}
-
-if [ ! $# == 1 ]; then
- echo "Usage: perf_cpu.sh sample_interval"
- exit
-fi
-
-ts=0
-interval=$1
-perf_cpu
diff --git a/collection/perf-memBW.sh b/collection/perf-memBW.sh
deleted file mode 100644
index 5987a96..0000000
--- a/collection/perf-memBW.sh
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/bin/bash
-
-function perf_Mem_bw () {
-
- if dmidecode -t processor | grep -q -E 'Kunpeng|Hisilicon' ; then
-
- CPU0_Die0_BW_R="hisi_sccl1_ddrc0/flux_rd/,hisi_sccl1_ddrc1/flux_rd/,hisi_sccl1_ddrc2/flux_rd/,hisi_sccl1_ddrc3/flux_rd/"
- CPU0_Die0_BW_W="hisi_sccl1_ddrc0/flux_wr/,hisi_sccl1_ddrc1/flux_wr/,hisi_sccl1_ddrc2/flux_wr/,hisi_sccl1_ddrc3/flux_wr/"
- CPU0_Die1_BW_R="hisi_sccl3_ddrc0/flux_rd/,hisi_sccl3_ddrc1/flux_rd/,hisi_sccl3_ddrc2/flux_rd/,hisi_sccl3_ddrc3/flux_rd/"
- CPU0_Die1_BW_W="hisi_sccl3_ddrc0/flux_wr/,hisi_sccl3_ddrc1/flux_wr/,hisi_sccl3_ddrc2/flux_wr/,hisi_sccl3_ddrc3/flux_wr/"
-
- CPU1_Die0_BW_R="hisi_sccl5_ddrc0/flux_rd/,hisi_sccl5_ddrc1/flux_rd/,hisi_sccl5_ddrc2/flux_rd/,hisi_sccl5_ddrc3/flux_rd/"
- CPU1_Die0_BW_W="hisi_sccl5_ddrc0/flux_wr/,hisi_sccl5_ddrc1/flux_wr/,hisi_sccl5_ddrc2/flux_wr/,hisi_sccl5_ddrc3/flux_wr/"
- CPU1_Die1_BW_R="hisi_sccl7_ddrc0/flux_rd/,hisi_sccl7_ddrc1/flux_rd/,hisi_sccl7_ddrc2/flux_rd/,hisi_sccl7_ddrc3/flux_rd/"
- CPU1_Die1_BW_W="hisi_sccl7_ddrc0/flux_wr/,hisi_sccl7_ddrc1/flux_wr/,hisi_sccl7_ddrc2/flux_wr/,hisi_sccl7_ddrc3/flux_wr/"
-
- BW_Events=" $CPU0_Die0_BW_R,$CPU0_Die0_BW_W,$CPU0_Die1_BW_R,$CPU0_Die1_BW_W,$CPU1_Die0_BW_R,$CPU1_Die0_BW_W,$CPU1_Die1_BW_R,$CPU1_Die1_BW_W"
- else
-
- echo "not Support This CPU Architecture..."
- exit
-
- fi
-
- let interval=$interval*1000
-
- timeout $ts perf stat -x ',' -a -I $interval -e $BW_Events 2>&1 | \
- awk -F, '
- BEGIN {
- tpre=-1;
- first=1;
- }
- {
- tcurr=$1;
- if(first==1)
- {
- tpre=tcurr;
- first=0;
- printf("#################################Start to monitor The System DDR Bandwidth##################################################\n");
- printf(" MEM_Total CPU0 CPU1 CPU0_Die0 CPU0_Die1 CPU1_Die0 CPU1_Die1 MEM_CPU0_Die0_R MEM_CPU0_Die1_R MEM_CPU1_Die0_R MEM_CPU1_Die1_R MEM_CPU0_Die0_W MEM_CPU0_Die1_W MEM_CPU1_Die0_W MEM_CPU1_Die1_W\n");
- }
-
- if(tcurr != tpre)
- {
-
- MEM_CPU0_Die0_R = CPU0_Die0_R*32/1024/1024;
- MEM_CPU0_Die1_R = CPU0_Die1_R*32/1024/1024;
- MEM_CPU1_Die0_R = CPU1_Die0_R*32/1024/1024;
- MEM_CPU1_Die1_R = CPU1_Die1_R*32/1024/1024;
-
- MEM_CPU0_Die0_W = CPU0_Die0_W*32/1024/1024;
- MEM_CPU0_Die1_W = CPU0_Die1_W*32/1024/1024;
- MEM_CPU1_Die0_W = CPU1_Die0_W*32/1024/1024;
- MEM_CPU1_Die1_W = CPU1_Die1_W*32/1024/1024;
-
- MEM_CPU0_Die0 = MEM_CPU0_Die0_R + MEM_CPU0_Die0_W;
- MEM_CPU0_Die1 = MEM_CPU0_Die1_R + MEM_CPU0_Die1_W;
-
- MEM_CPU1_Die0 = MEM_CPU1_Die0_R + MEM_CPU1_Die0_W;
- MEM_CPU1_Die1 = MEM_CPU1_Die1_R + MEM_CPU1_Die1_W;
-
- MEM_CPU0 = MEM_CPU0_Die0_R + MEM_CPU0_Die0_W + MEM_CPU0_Die1_R + MEM_CPU0_Die1_W;
- MEM_CPU1 = MEM_CPU1_Die0_R + MEM_CPU1_Die0_W + MEM_CPU1_Die1_R + MEM_CPU1_Die1_W;
-
- MEM_Total = MEM_CPU0 + MEM_CPU1;
-
- printf("%10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f\n",MEM_Total,MEM_CPU0,MEM_CPU1,MEM_CPU0_Die0,MEM_CPU0_Die1,MEM_CPU1_Die0,MEM_CPU1_Die1,MEM_CPU0_Die0_R,MEM_CPU0_Die1_R,MEM_CPU1_Die0_R,MEM_CPU1_Die1_R,MEM_CPU0_Die0_W,MEM_CPU0_Die1_W,MEM_CPU1_Die0_W,MEM_CPU1_Die1_W);
-
- CPU0_Die0_R=0;
- CPU0_Die0_W=0;
- CPU0_Die1_R=0;
- CPU0_Die1_W=0;
- CPU1_Die0_R=0;
- CPU1_Die0_W=0;
- CPU1_Die1_R=0;
- CPU1_Die1_W=0;
-
- tpre=tcurr;
-
- }
-
- switch ($4)
- {
- case /sccl1.*rd/:
- CPU0_Die0_R += $2;
- break;
- case /sccl1.*wr/:
- CPU0_Die0_W += $2;
- break;
- case /sccl3.*rd/:
- CPU0_Die1_R += $2;
- break;
- case /sccl3.*wr/:
- CPU0_Die1_W += $2;
- break;
- case /sccl5.*rd/:
- CPU1_Die0_R += $2;
- break;
- case /sccl5.*wr/:
- CPU1_Die0_W += $2;
- break;
- case /sccl7.*rd/:
- CPU1_Die1_R += $2;
- break;
- case /sccl7.*wr/:
- CPU1_Die1_W += $2;
- break;
- }
-
- }
- '
-
-}
-
-
-if [ ! $# == 1 ]; then
- echo "Usage: perf_mem.sh sample_interval"
- exit
-fi
-
-
-ts=0
-interval=$1
-perf_Mem_bw
-
diff --git a/common/checker/checker.go b/common/checker/checker.go
deleted file mode 100644
index 6728fa6..0000000
--- a/common/checker/checker.go
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package checker
-
-import (
- PB "atune/api/profile"
- "atune/common/log"
- "atune/common/utils"
- "encoding/xml"
- "fmt"
- "io/ioutil"
- "os"
- "regexp"
- "strconv"
-)
-
-// MemTopo represent the memory topology type
-type MemTopo struct {
- Path string
-}
-
-type children struct {
- ID string `xml:"id"`
- Class string `xml:"class"`
- Claimed bool `xml:"claimed"`
- Handle string `xml:"handle"`
- Description string `xml:"description"`
- Product string `xml:"product"`
- Vendor string `xml:"vendor"`
- Physid string `xml:"physid"`
- Serial string `xml:"serial"`
- Slot string `xml:"slot"`
- Units string `xml:"units"`
- Size int64 `xml:"size"`
- Width int `xml:"width"`
- Clock int64 `xml:"clock"`
-}
-
-type memorysInfo struct {
- ID string `xml:"id"`
- Physid string `xml:"physid"`
- Childrens []children `xml:"children"`
-}
-
-type topology struct {
- XMLName xml.Name `xml:"topology"`
- Memorys []memorysInfo `xml:"memorys"`
-}
-
-/*
-Check method check the memory topolog, whether the memory interpolation is balanced.
-*/
-func (m *MemTopo) Check(ch chan *PB.AckCheck) error {
- file, err := os.Open(m.Path)
- if err != nil {
- return err
- }
-
- defer file.Close()
-
- data, err := ioutil.ReadAll(file)
- if err != nil {
- return err
- }
-
- topology := topology{}
- err = xml.Unmarshal(data, &topology)
- if err != nil {
- return err
- }
-
- reg := regexp.MustCompile(`DIMM.*?(\d)(\d)(\d)\s.*`)
- var size int64
- memNum := 0
- size = 0
-
- maxSocket := 0
- maxChannel := 0
- maxSlot := 0
-
- for _, memory := range topology.Memorys {
- for _, child := range memory.Childrens {
- if params := reg.FindStringSubmatch(child.Slot); params != nil {
- socket, _ := strconv.Atoi(params[1])
- channel, _ := strconv.Atoi(params[2])
- slot, _ := strconv.Atoi(params[3])
- if socket > maxSocket {
- maxSocket = socket
- }
- if channel > maxChannel {
- maxChannel = channel
- }
- if slot > maxSlot {
- maxSlot = slot
- }
- }
- }
- }
-
- memTotal := (maxSocket + 1) * (maxChannel + 1) * (maxSlot + 1)
- memLocation := make([]bool, memTotal)
-
- for _, memory := range topology.Memorys {
- for _, child := range memory.Childrens {
- if child.Size != 0 {
- if params := reg.FindStringSubmatch(child.Slot); params != nil {
- socket, _ := strconv.Atoi(params[1])
- channel, _ := strconv.Atoi(params[2])
- slot, _ := strconv.Atoi(params[3])
- index := socket*(maxChannel+1)*(maxSlot+1) + channel*(maxSlot+1) + slot
- memLocation[index] = true
- }
-
- memNum++
- if size != 0 && child.Size != size {
- sendChanToAdm(ch, "memory sieze", utils.FAILD, "memory size is not the same")
- } else if size == 0 {
- size = child.Size
- }
- }
- }
- }
-
- log.Infof("memory total num is : %d", memNum)
- log.Info("memory location is:", memNum)
-
- if memNum == memTotal {
- sendChanToAdm(ch, "memory number", utils.SUCCESS, fmt.Sprintf("memory num is %d", memNum))
- return nil
- }
-
- if memNum%(maxChannel+1) != 0 {
- sendChanToAdm(ch, "memory number", utils.FAILD, fmt.Sprintf("memory num is %d, not recommend, recommand 8,16 or 32", memNum))
- return nil
- }
-
- memHalf := memTotal / 2
-
- for i := 0; i < memHalf; i++ {
- if memLocation[i] != memLocation[i+memHalf] {
- sendChanToAdm(ch, "memory location", utils.FAILD, fmt.Sprintf("memory location maybe not balanced"))
- return nil
- }
- }
- sendChanToAdm(ch, "memory location", utils.SUCCESS, "OK")
- return nil
-}
-
-func sendChanToAdm(ch chan *PB.AckCheck, item string, status string, description string) {
- if ch == nil {
- return
- }
-
- ch <- &PB.AckCheck{Name: item, Status: status, Description: description}
-}
diff --git a/common/checker/elf.go b/common/checker/elf.go
deleted file mode 100644
index 4d4aecd..0000000
--- a/common/checker/elf.go
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package checker
-
-import (
- PB "atune/api/profile"
- "atune/common/log"
- "atune/common/utils"
-)
-
-//ELF file structer
-type ELF struct {
- FileName string
-}
-
-/*
-Check method check the elf file format
-*/
-func (elf *ELF) Check(ch chan *PB.AckCheck) error {
- log.Debug("Check %s", elf.FileName)
-
- sendChanToAdm(ch, elf.FileName, utils.SUCCESS, "FIXME: NOT Implement")
-
- return nil
-}
diff --git a/common/client/client.go b/common/client/client.go
deleted file mode 100644
index 2bd8cd7..0000000
--- a/common/client/client.go
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package client
-
-import (
- "atune/common/config"
- "fmt"
- "os"
- "time"
-
- "github.com/urfave/cli"
- "google.golang.org/grpc"
-)
-
-type clientOpts struct {
- defaultns string
- dialOptions []grpc.DialOption
-}
-
-// Opt allows callers to set options on the client
-type Opt func(c *clientOpts) error
-
-//Client :The grpc client structer
-type Client struct {
- conn *grpc.ClientConn
- defaultns string
- services map[string]interface{}
-}
-
-// GetService method return the grpc client command plugin service
-func (c *Client) GetService(name string) (interface{}, error) {
- _, ok := c.services[name]
- if !ok {
- return nil, fmt.Errorf("There is no service %s available", name)
- }
-
- return c.services[name], nil
-}
-
-// NewService method call the function to new a grpc client plugin service
-func (c *Client) NewService(name string, fn func(cc *grpc.ClientConn) (interface{}, error)) error {
- if _, ok := c.services[name]; ok {
- return fmt.Errorf("Service %s client has existed")
- }
- svc, err := fn(c.conn)
- if err != nil {
- return err
- }
-
- c.services[name] = svc
-
- return nil
-}
-
-// Connection method return the grpc connection of the client
-func (c *Client) Connection() *grpc.ClientConn {
- return c.conn
-}
-
-//Close method close the grpc connection
-func (c *Client) Close() {
- c.conn.Close()
-}
-
-//GetState method return the state of the grpc connection
-func (c *Client) GetState() string {
- return c.conn.GetState().String()
-}
-
-//NewWithConn method create a grpc client depend the connection
-func NewWithConn(conn *grpc.ClientConn, opts ...Opt) (*Client, error) {
- return &Client{
- conn: conn,
- services: make(map[string]interface{}),
- }, nil
-}
-
-//NewClientFromContext method create a grpc client depend the command context
-func NewClientFromContext(ctx *cli.Context, opts ...Opt) (*Client, error) {
- addr, port := parseAddr(ctx)
- return newClient(addr+":"+port, opts...)
-}
-
-// NewClientWithoutCli method create a grpc client depend the address and port
-func NewClientWithoutCli(addr string, port string, opts ...Opt) (*Client, error) {
- if addr == config.DefaultTgtAddr {
- addr, _ = ParseEnvAddr()
- }
- if port == config.DefaultTgtPort {
- _, port = ParseEnvAddr()
- }
- return newClient(addr+":"+port, opts...)
-}
-
-//NewClientFromConn method create a grpc client depend the conn, which is address:port format
-func NewClientFromConn(conn string, opts ...Opt) (*Client, error) {
- return newClient(conn, opts...)
-}
-
-//NewClient method create a grpc client depend the address and port
-func NewClient(addr string, port string, opts ...Opt) (*Client, error) {
- return newClient(addr+":"+port, opts...)
-}
-
-func newClient(address string, opts ...Opt) (*Client, error) {
- var copts clientOpts
- for _, o := range opts {
- if err := o(&copts); err != nil {
- return nil, err
- }
- }
- gopts := []grpc.DialOption{
- grpc.WithBlock(),
- grpc.WithInsecure(),
- grpc.WithTimeout(60 * time.Second),
- grpc.FailOnNonTempDialError(true),
- grpc.WithBackoffMaxDelay(3 * time.Second),
- }
- if len(copts.dialOptions) > 0 {
- gopts = copts.dialOptions
- }
- conn, err := grpc.Dial(address, gopts...)
- if err != nil {
- return nil, fmt.Errorf("failed to dial %q : %s", address, err)
- }
- return NewWithConn(conn, opts...)
-}
-
-//ParseEnvAddr method return the ip and port depend the Env, if not return the default value
-func ParseEnvAddr() (string, string) {
- addr := os.Getenv(config.EnvAddr)
- if addr == "" {
- addr = config.DefaultTgtAddr
- }
-
- port := os.Getenv(config.EnvPort)
- if port == "" {
- port = config.DefaultTgtPort
- }
-
- return addr, port
-}
-
-//ParseCliAddr method return the ip and port depend the command context
-func ParseCliAddr(ctx *cli.Context) (string, string) {
- return ctx.GlobalString("address"), ctx.GlobalString("port")
-}
-
-func parseAddr(ctx *cli.Context) (string, string) {
- addr, port := ParseCliAddr(ctx)
-
- if addr == config.DefaultTgtAddr {
- addr, _ = ParseEnvAddr()
- }
- if port == config.DefaultTgtPort {
- _, port = ParseEnvAddr()
- }
-
- return addr, port
-}
diff --git a/common/config/config.go b/common/config/config.go
deleted file mode 100644
index 5cf30ce..0000000
--- a/common/config/config.go
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package config
-
-import (
- "atune/common/log"
- "atune/common/utils"
- "fmt"
- "path"
- "path/filepath"
- "strings"
-
- "github.com/go-ini/ini"
-)
-
-// application common config
-const (
- Version = "0.0.1"
-
- EnvAddr = "ATUNED_ADDR"
- EnvPort = "ATUNED_PORT"
-
- DefaultTgtPort = "60001"
- DefaultTgtAddr = "127.0.0.1"
-)
-
-// default path config
-const (
- DefaultPath = "/usr/lib/atuned/"
- DefaultModDaemonSvrPath = DefaultPath + "modules"
- DefaultConfPath = "/etc/atuned/"
- DefaultScriptPath = "/usr/libexec/atuned/scripts"
- DefaultCollectorPath = "/usr/libexec/atuned/collector"
- DefaultAnalysisPath = "/usr/libexec/atuned/analysis"
- DefaultTempPath = "/tmp/atuned"
- DefaultCheckerPath = "/usr/share/atuned/checker/"
- DefaultBackupPath = "/usr/share/atuned/backup/"
-)
-
-// log config
-const (
- LogPath = "/var/log/atuned"
- LogFileName = "atuned.log"
- Formatter = "text"
- Modes = "syslog"
-)
-
-// python service url
-const (
- Protocol string = "http"
- LocalHost string = "127.0.0.1"
- ApiVersion string = "v1"
-
- ConfiguratorURI string = "setting"
- MonitorURI string = "monitor"
- OptimizerURI string = "optimizer"
- CollectorURI string = "collector"
- ClassificationURI string = "classification"
- ProfileURI string = "profile"
- TrainingURI string = "training"
-)
-
-// database config
-const (
- DatabasePath string = "/var/lib/atuned"
- DatabaseType string = "sqlite3"
- DatabaseName string = "atuned.db"
-)
-
-// monitor config
-const (
- FileFormat string = "xml"
-)
-
-// the grpc server config
-var (
- Address string
- Port string
- RestPort string
-)
-
-// Cfg type, the type that load the conf file
-type Cfg struct {
- Raw *ini.File
-}
-
-//Load method load the default conf file
-func (c *Cfg) Load() error {
- defaultConfigFile := path.Join(DefaultConfPath, "atuned.cnf")
-
- exist, err := utils.PathExist(defaultConfigFile)
- if err != nil {
- return err
- }
- if !exist {
- return fmt.Errorf("Could not find default config file")
- }
-
- cfg, err := ini.Load(defaultConfigFile)
- if err != nil {
- return fmt.Errorf("Faild to parse %s, %v", defaultConfigFile, err)
- }
-
- c.Raw = cfg
-
- section := cfg.Section("server")
- Address = section.Key("address").MustString("127.0.0.1")
- Port = section.Key("port").MustString("60001")
- RestPort = section.Key("rest_port").MustString("8383")
-
- /*
- interval, err := section.Key("interval").Int()
- if err != nil {
- return fmt.Errorf("interval value must be a interger between 1800 and 7200")
- }
-
- if interval < 1800 || interval > 7200 {
- return fmt.Errorf("interval value must be a interger between 1800 and 7200")
- }
- */
-
- if err := initLogging(cfg); err != nil {
- return err
- }
-
- return nil
-}
-
-//NewCfg method create the cfg struct that store the conf file
-func NewCfg() *Cfg {
- return &Cfg{
- Raw: ini.Empty(),
- }
-}
-
-func initLogging(cfg *ini.File) error {
- modes := strings.Split(Modes, ",")
- logPath := cfg.Section("log").Key("path").String()
- if !filepath.IsAbs(logPath) {
- return fmt.Errorf("log path must be absolute path")
- }
- log.InitLogger(modes, logPath, cfg)
-
- return nil
-}
-
-// GetUrl return the url
-func GetUrl(uri string) string {
- url := fmt.Sprintf("%s://%s:%s/%s/%s", Protocol, LocalHost, RestPort, ApiVersion, uri)
- return url
-}
diff --git a/common/http/client.go b/common/http/client.go
deleted file mode 100644
index 0c461f3..0000000
--- a/common/http/client.go
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package http
-
-import (
- "bytes"
- "encoding/json"
- "io"
- "net/http"
- "strings"
-)
-
-//HTTPClient :the structer that encapsulation the net/http package
-type httpClient struct {
- client *http.Client
-}
-
-//Do method do the action send the data to the http server
-func (c *httpClient) Do(req *http.Request) (*http.Response, error) {
- response, err := c.client.Do(req)
- return response, err
-}
-
-func newhttpClient() *httpClient {
- var client *http.Client
-
- client = &http.Client{}
-
- return &httpClient{
- client: client,
- }
-
-}
-
-func newRequest(method string, url string, body interface{}) (*http.Request, error) {
- var reader io.Reader
-
- switch body.(type) {
- case string:
- reader = strings.NewReader(body.(string))
- case []byte:
- reader = bytes.NewReader(body.([]byte))
- default:
- bytesData, err := json.Marshal(body)
- if err != nil {
- return nil, err
- }
- reader = bytes.NewReader(bytesData)
-
- }
-
- request, err := http.NewRequest(method, url, reader)
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- if err != nil {
- return nil, err
- }
-
- request.Header.Add("Content-Type", "application/json")
-
- return request, nil
-}
-
-// Get method call the restfull GET method
-func Get(url string, data interface{}) (*http.Response, error) {
- restClient := newhttpClient()
- req, err := newRequest("GET", url, data)
- if err != nil {
- return nil, err
- }
-
- response, err := restClient.Do(req)
- if err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-//Post method call the restfull POST method
-func Post(url string, data interface{}) (*http.Response, error) {
- restClient := newhttpClient()
- req, err := newRequest("POST", url, data)
- if err != nil {
- return nil, err
- }
-
- response, err := restClient.Do(req)
- if err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-// Put method call the restfull PUT method
-func Put(url string, data interface{}) (*http.Response, error) {
- restClient := newhttpClient()
- req, err := newRequest("PUT", url, data)
- if err != nil {
- return nil, err
- }
-
- response, err := restClient.Do(req)
- if err != nil {
- return nil, err
- }
-
- return response, nil
-}
-
-// Delete method call the restfull DELETE method
-func Delete(url string) (*http.Response, error) {
- restClient := newhttpClient()
- req, err := newRequest("DELETE", url, nil)
- if err != nil {
- return nil, err
- }
-
- response, err := restClient.Do(req)
- if err != nil {
- return nil, err
- }
-
- return response, nil
-}
diff --git a/common/log/interface.go b/common/log/interface.go
deleted file mode 100644
index 9fec0d3..0000000
--- a/common/log/interface.go
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package log
-
-// Logger is the interface for logger
-type Logger interface {
- Debug(...interface{})
- Debugln(...interface{})
- Debugf(string, ...interface{})
-
- Info(...interface{})
- Infoln(...interface{})
- Infof(string, ...interface{})
-
- Warn(...interface{})
- Warnln(...interface{})
- Warnf(string, ...interface{})
-
- Error(...interface{})
- Errorln(...interface{})
- Errorf(string, ...interface{})
-
- Fatal(...interface{})
- Fatalln(...interface{})
- Fatalf(string, ...interface{})
-
- With(key string, value interface{}) Logger
-
- SetLevel(string) error
-}
diff --git a/common/log/log.go b/common/log/log.go
deleted file mode 100644
index f8b7a29..0000000
--- a/common/log/log.go
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package log
-
-import (
- "fmt"
- "log/syslog"
- "os"
- "path/filepath"
- "runtime"
-
- "github.com/go-ini/ini"
- logrus "github.com/sirupsen/logrus"
- logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
-)
-
-type logger struct {
- entry *logrus.Entry
-}
-
-var rootLogger = logrus.New()
-var baseLogger = logger{entry: logrus.NewEntry(rootLogger)}
-
-var logLevels = map[string]logrus.Level{
- "panic": logrus.PanicLevel,
- "fatal": logrus.FatalLevel,
- "error": logrus.ErrorLevel,
- "warn": logrus.WarnLevel,
- "info": logrus.InfoLevel,
- "debug": logrus.DebugLevel,
- "trace": logrus.TraceLevel,
-}
-
-// InitLogger method init the base logger
-func InitLogger(modes []string, logPath string, cfg *ini.File) error {
- sec, err := cfg.GetSection("log")
- if err != nil {
- return err
- }
- formatter := getLogFormat("text")
-
- baseLogger.SetLevel(sec.Key("level").MustString("info"))
- for _, mode := range modes {
-
- switch mode {
- case "console":
- baseLogger.entry.Logger.Out = os.Stdout
- baseLogger.entry.Logger.Formatter = formatter
- case "syslog":
- syslogHook, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "atuned")
- if err != nil {
- baseLogger.Errorf("syslog hook init faild:%v", err)
- }
- baseLogger.entry.Logger.AddHook(syslogHook)
-
- }
- }
-
- return nil
-}
-
-func (log logger) withFileField() *logrus.Entry {
- filename, line := "???", 0
- _, filename, line, ok := runtime.Caller(2)
- if ok {
- filename = filepath.Base(filename)
- }
- return log.entry.WithField("file", fmt.Sprintf("%s:%d", filename, line))
-}
-
-func (log logger) With(key string, value interface{}) Logger {
- return logger{log.entry.WithField(key, value)}
-}
-
-func (log logger) Debug(args ...interface{}) {
- log.withFileField().Debug(args...)
-}
-
-func (log logger) Debugln(args ...interface{}) {
- log.withFileField().Debugln(args...)
-}
-
-func (log logger) Debugf(format string, args ...interface{}) {
- log.withFileField().Debugf(format, args...)
-}
-
-func (log logger) Info(args ...interface{}) {
- log.withFileField().Info(args...)
-}
-
-func (log logger) Infoln(args ...interface{}) {
- log.withFileField().Infoln(args...)
-}
-
-func (log logger) Infof(format string, args ...interface{}) {
- log.withFileField().Infof(format, args...)
-}
-
-func (log logger) Warn(args ...interface{}) {
- log.withFileField().Warn(args...)
-}
-
-func (log logger) Warnln(args ...interface{}) {
- log.withFileField().Warnln(args...)
-}
-
-func (log logger) Warnf(format string, args ...interface{}) {
- log.withFileField().Warnf(format, args...)
-}
-
-func (log logger) Error(args ...interface{}) {
- log.withFileField().Error(args...)
-}
-
-func (log logger) Errorln(args ...interface{}) {
- log.withFileField().Errorln(args...)
-}
-
-func (log logger) Errorf(format string, args ...interface{}) {
- log.withFileField().Errorf(format, args...)
-}
-
-func (log logger) Fatal(args ...interface{}) {
- log.withFileField().Fatal(args...)
-}
-
-func (log logger) Fatalln(args ...interface{}) {
- log.withFileField().Fatalln(args...)
-}
-
-func (log logger) Fatalf(format string, args ...interface{}) {
- log.withFileField().Fatalf(format, args...)
-}
-
-func (log logger) SetLevel(level string) error {
- lev, err := logrus.ParseLevel(level)
- if err != nil {
- return err
- }
-
- log.entry.Logger.SetLevel(lev)
- return nil
-}
-
-// GetLogger method return the root logger of the logger service
-func GetLogger() *logrus.Logger {
-
- return rootLogger
-}
-
-func getLogFormat(format string) logrus.Formatter {
- switch format {
- case "text":
- return &logrus.TextFormatter{}
- case "json":
- return &logrus.JSONFormatter{}
- default:
- return &logrus.TextFormatter{}
-
- }
-}
-
-// Debug method log debug level args
-func Debug(args ...interface{}) {
- baseLogger.withFileField().Debug(args...)
-}
-
-// Debugln method log debug level args
-func Debugln(args ...interface{}) {
- baseLogger.withFileField().Debugln(args...)
-}
-
-// Debugf method log debug level message with format string
-func Debugf(format string, args ...interface{}) {
- baseLogger.withFileField().Debugf(format, args...)
-}
-
-// Info method log info level args
-func Info(args ...interface{}) {
- baseLogger.withFileField().Info(args...)
-}
-
-// Infoln method log info level args
-func Infoln(args ...interface{}) {
- baseLogger.withFileField().Infoln(args...)
-}
-
-// Infof method log info level message with format string
-func Infof(format string, args ...interface{}) {
- baseLogger.withFileField().Infof(format, args...)
-}
-
-// Warn method log warn args
-func Warn(args ...interface{}) {
- baseLogger.withFileField().Warn(args...)
-}
-
-// Warnln method log warn args
-func Warnln(args ...interface{}) {
- baseLogger.withFileField().Warnln(args...)
-}
-
-// Warnf method log warn level message with format string
-func Warnf(format string, args ...interface{}) {
- baseLogger.withFileField().Warnf(format, args...)
-}
-
-// Error method log error args
-func Error(args ...interface{}) {
- baseLogger.withFileField().Error(args...)
-}
-
-// Errorln method log error args
-func Errorln(args ...interface{}) {
- baseLogger.withFileField().Errorln(args...)
-}
-
-// Errorf method log error level message with format string
-func Errorf(format string, args ...interface{}) {
- baseLogger.withFileField().Errorf(format, args...)
-}
-
-// Fatal method log fatal info
-func Fatal(args ...interface{}) {
- baseLogger.withFileField().Fatal(args...)
-}
-
-// Fatalln method log fatal info
-func Fatalln(args ...interface{}) {
- baseLogger.withFileField().Fatalln(args...)
-}
-
-// Fatalf method log fatal level message with format string
-func Fatalf(format string, args ...interface{}) {
- baseLogger.withFileField().Fatalf(format, args...)
-}
-
-// WithField method add field to logger
-func WithField(key string, value interface{}) Logger {
- return baseLogger.With(key, value)
-}
diff --git a/common/models/profile.go b/common/models/profile.go
deleted file mode 100644
index be856a8..0000000
--- a/common/models/profile.go
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package models
-
-import (
- "atune/common/config"
- "atune/common/http"
- "encoding/json"
- "fmt"
- "io/ioutil"
-)
-
-// Profile : the data that send to http backup and resume service
-type Profile struct {
- Section string `json:"section"`
- Config string `json:"config"`
- Path string `json:"path"`
-}
-
-//RespBody : the returned value of the backup or resume method
-type RespBody struct {
- Status string `json:"status"`
- Value string `json:"value"`
-}
-
-//Backup method the value specified by the Prfile
-func (p *Profile) Backup() (*RespBody, error) {
- url := config.GetUrl(config.ProfileURI)
- res, err := http.Get(url, p)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
-
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("backup profile %s failed", p.Config)
- }
-
- respData, err := ioutil.ReadAll(res.Body)
- respIns := new(RespBody)
- err = json.Unmarshal(respData, respIns)
- if err != nil {
- return nil, err
- }
- return respIns, nil
-}
-
-//Resume method resume the value specified by the Prfile
-func (p *Profile) Resume() (*RespBody, error) {
- url := config.GetUrl(config.ProfileURI)
- res, err := http.Put(url, p)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
-
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("resume config %s failed", p.Config)
- }
-
- respData, err := ioutil.ReadAll(res.Body)
- respIns := new(RespBody)
- err = json.Unmarshal(respData, respIns)
- if err != nil {
- return nil, err
- }
- return respIns, nil
-}
diff --git a/common/models/training.go b/common/models/training.go
deleted file mode 100644
index 59663fc..0000000
--- a/common/models/training.go
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package models
-
-import (
- "atune/common/config"
- "atune/common/http"
- "fmt"
-)
-
-// Training : The data that send to http service for training
-type Training struct {
- DataPath string `json:"datapath"`
- ModelPath string `json:"modelpath"`
- OutputPath string `json:"outputpath"`
-}
-
-// Post method call training service
-func (t *Training) Post() (bool, error) {
- url := config.GetUrl(config.TrainingURI)
- response, err := http.Post(url, t)
- if err != nil {
- return false, err
- }
-
- defer response.Body.Close()
- if response.StatusCode != 200 {
- return false, fmt.Errorf("training data faild")
- }
-
- return true, nil
-}
diff --git a/common/profile/factory.go b/common/profile/factory.go
deleted file mode 100644
index 9246b25..0000000
--- a/common/profile/factory.go
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- "github.com/go-ini/ini"
-)
-
-// Create method create the Profile structer
-// name is the workloadType name
-// path is the profile path which can be removed in the future
-func Create(name string, path string, config *ini.File) Profile {
- profile := Profile{
- name: name,
- path: path,
- config: config,
- }
-
- if config == nil {
- return profile
- }
-
- for _, section := range config.Sections() {
- if section.Name() == "DEFAULT" {
- continue
- }
-
- if section.Name() == "main" {
- profile.options = section
- } else {
- profile.units = append(profile.units, section)
- }
- }
-
- return profile
-}
diff --git a/common/profile/loader.go b/common/profile/loader.go
deleted file mode 100644
index b76079b..0000000
--- a/common/profile/loader.go
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- CONF "atune/common/config"
- "atune/common/log"
- "atune/common/sqlstore"
- "fmt"
- "path"
- "regexp"
- "strings"
-
- "github.com/go-ini/ini"
-)
-
-func filter(vs []string) []string {
- regex := regexp.MustCompile("^[a-zA-Z0-9_.-]+$")
- vsf := make([]string, 0)
-
- for _, v := range vs {
- if regex.MatchString(v) {
- vsf = append(vsf, v)
- }
- }
-
- return vsf
-}
-
-/*
-Load profile_names slice, and it's include profiles, the profiles slice returned must be in order.
-The profile inherit from it's include profile, make sure the include profile behind the main profile,
-and not override by the include profile.
-*/
-func loadProfile(profileNames []string, profiles []Profile, processedProfiles []string, included bool) ([]Profile, []string) {
- for _, name := range profileNames {
- name = strings.Trim(name, " ")
-
- processedProfiles = append(processedProfiles, name)
-
- config, err := loadConfigData(name)
- if err != nil {
- fmt.Println("Failure to load_config_data")
- continue
- }
- profile := Create(name, name, config)
-
- profiles = append(profiles, profile)
- if profile.options != nil {
- if profile.options.HasKey("include") {
- include, _ := profile.options.GetKey("include")
- names := make([]string, 0)
- names = append(names, strings.Trim(include.Value(), ""))
- profiles, processedProfiles = loadProfile(names, profiles, processedProfiles, true)
- }
- }
- profile.included = included
-
- }
-
- return profiles, processedProfiles
-}
-
-func isInclude(section string, profile Profile) (int, bool) {
- var index = 0
- for index, unit := range profile.units {
- if unit.Name() == section {
- return index, true
- }
- }
-
- return index, false
-}
-
-func merge(profiles []Profile) Profile {
- final := profiles[0]
-
- // Ingnore included profile name
- if final.included {
- final.name = ""
- final.path = ""
- }
-
- for i, profile := range profiles {
- if i == 0 { // Ignore first element: final
- continue
- }
-
- // Process Options
- if profile.options != nil {
- for _, key := range profile.options.Keys() {
- if key.Name() == "include" {
- continue
- }
-
- if final.options == nil {
- final.options, _ = final.config.NewSection("main")
- }
- final.options.NewKey(key.Name(), key.Value())
-
- section, _ := final.config.GetSection("main")
- section.NewKey(key.Name(), key.Value())
- }
- }
-
- // Process Units
- for _, unit := range profile.units {
- index, include := isInclude(unit.Name(), final)
- if !include {
- final.units = append(final.units, unit)
-
- section, _ := final.config.NewSection(unit.Name())
- for _, key := range unit.Keys() {
- section.NewKey(key.Name(), key.Value())
- }
- } else {
- section, _ := final.config.GetSection(unit.Name())
- for _, key := range unit.Keys() {
- if final.units[index].HasKey(key.Name()) {
- /*FIXME: Ignore the same key*/
- continue
- } else {
- final.units[index].NewKey(key.Name(), key.Value())
- section.NewKey(key.Name(), key.Value())
- }
- }
- }
- }
-
- // Process inputs parameter
- if profile.inputs != nil {
- for _, key := range profile.inputs.Keys() {
- if final.inputs == nil {
- final.inputs, _ = final.config.NewSection("inputs")
- }
- final.inputs.NewKey(key.Name(), key.Value())
-
- section, _ := final.config.GetSection("inputs")
- section.NewKey(key.Name(), key.Value())
- }
- }
- //
- if !profile.included {
- final.name = final.name + " " + profile.name
- final.path = final.path + "," + profile.path
- }
- }
-
- return final
-}
-
-// LoadFromWorkloadType method load the profile content depned the workload type
-func LoadFromWorkloadType(workloadType string) (Profile, bool) {
- classProfile := &sqlstore.GetClass{Class: workloadType}
- err := sqlstore.GetClasses(classProfile)
- if err != nil {
- log.Errorf("inquery class_profile table faild")
- return Profile{}, false
- }
- if len(classProfile.Result) == 0 {
- log.Errorf("%s is not exist in the class_profile table", workloadType)
- return Profile{}, false
- }
-
- profileType := classProfile.Result[0].ProfileType
- profileNames := strings.Split(profileType, ",")
-
- pro, exist := Load(profileNames)
- pro.name = workloadType
- return pro, exist
-}
-
-// Load method load the profile content depned the profile names list
-func Load(profileNames []string) (Profile, bool) {
- profileNames = filter(profileNames)
- if len(profileNames) == 0 {
- fmt.Println("No profile or invaild profiles were specified.")
- return Profile{}, false
- }
-
- profiles := make([]Profile, 0)
- processedProfiles := make([]string, 0)
- profiles, processedProfiles = loadProfile(profileNames, profiles, processedProfiles, false)
-
- if len(profiles) == 0 {
- return Profile{}, false
- }
- finalProfile := merge(profiles)
-
- defaultConfigFile := path.Join(CONF.DefaultConfPath, "atuned.cnf")
- cfg, _ := ini.Load(defaultConfigFile)
- finalProfile.inputs = cfg.Section("system")
-
- return finalProfile, true
-}
-
-func loadConfigData(name string) (*ini.File, error) {
- context, err := sqlstore.GetContext(name)
- if err != nil {
- fmt.Println("Canot find profile ", name)
- return nil, err
- }
-
- config, err := ini.Load([]byte(context))
- if err != nil {
- fmt.Println("Failure to load context", name)
- return nil, err
- }
-
- // Filter {i:PROFILE_DIR}
- //dir_name := path.Dir(filename)
- dirName := CONF.DefaultScriptPath
- regex := regexp.MustCompile("\\${i:PROFILE_DIR}")
- for _, section := range config.Sections() {
- for _, key := range section.Keys() {
- config.Section(section.Name()).Key(key.Name()).SetValue(regex.ReplaceAllString(key.Value(), dirName))
- }
- }
-
- // Filter script=
- for _, section := range config.Sections() {
- if section.Name() == "script" {
- if section.HasKey("shell") {
- key, _ := section.GetKey("shell")
- scriptPath := path.Join(dirName, strings.Trim(key.Value(), " "))
- config.Section(section.Name()).Key("shell").SetValue(scriptPath)
- }
- }
- }
-
- return config, nil
-}
diff --git a/common/profile/profile.go b/common/profile/profile.go
deleted file mode 100644
index 23d9bc2..0000000
--- a/common/profile/profile.go
+++ /dev/null
@@ -1,459 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "atune/common/models"
- "atune/common/schedule"
- "atune/common/sqlstore"
- "atune/common/utils"
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "regexp"
- "sort"
- "strings"
- "time"
-
- "github.com/go-ini/ini"
-)
-
-// Profile :profile implement setting profile
-type Profile struct {
- included bool
-
- name string
- path string
-
- options *ini.Section
- units []*ini.Section
-
- config *ini.File
-
- inputs *ini.Section
-
- items map[string]*ini.File
- backup bool
-}
-
-// ConfigPutBody :body send to CPI service
-type ConfigPutBody struct {
- Section string `json:"section"`
- Key string `json:"key"`
- Value string `json:"value"`
-}
-
-// RespPut ; response of call CPI service
-type RespPut struct {
- Status string `json:status`
- Value string `json:value`
-}
-
-// Put method set the key to value, both specified by ConfigPutBody
-func (c *ConfigPutBody) Put() (*RespPut, error) {
- url := config.GetUrl(config.ConfiguratorURI)
- res, err := http.Put(url, c)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("connect to configurator service faild")
- }
- resBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(RespPut)
- err = json.Unmarshal(resBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-
-}
-
-// Get method get the current value of the spefied key by ConfigPutBody
-func (c *ConfigPutBody) Get() (*RespPut, error) {
- url := config.GetUrl(config.ConfiguratorURI)
- res, err := http.Get(url, c)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("connect to configurator service faild")
- }
- resBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(RespPut)
- err = json.Unmarshal(resBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-
-}
-
-// Backup method backup the workload type of the Profile
-func (p *Profile) Backup() error {
- // NOTE: we only clone p and p.units exist.
- if (p == nil) || (p.units == nil) {
- return nil
- }
-
- timeUnix := time.Now().Format("2006_01_02_15_04_05")
- backedPath := path.Join(config.DefaultBackupPath, p.name+"_"+timeUnix)
- os.MkdirAll(backedPath, os.ModePerm)
-
- buf := bytes.NewBuffer(nil)
-
- for _, unit := range p.units {
- // Ignore the sections ["main", "DEFAULT", "bios"]
- if name := unit.Name(); (name == "main") || (name == "DEFAULT") || (name == "bios" || name == "tip") {
- continue
- }
-
- buf.WriteString("[" + unit.Name() + "]" + "\n")
-
- for _, key := range unit.Keys() {
- keyName := key.Name()
- keyName, err := p.replaceParameter(keyName)
- if err != nil {
- return err
- }
- keyValue, err := p.replaceParameter(key.Value())
- if err != nil {
- return err
- }
- config := keyName + "=" + keyValue
- body := &models.Profile{
- Section: unit.Name(),
- Config: config,
- Path: backedPath,
- }
-
- respPutIns, _ := body.Backup()
- if respPutIns == nil || (respPutIns.Status == "FAILED") {
- continue
- }
- buf.WriteString(keyName + "=" + respPutIns.Value + "\n")
- }
- }
-
- profileItems := &sqlstore.ProfileLog{
- ProfileID: p.name,
- Context: buf.String(),
- Timestamp: time.Now(),
- BackupPath: backedPath,
- }
-
- if err := sqlstore.InsertProfileLog(profileItems); err != nil {
- return err
- }
-
- return nil
-}
-
-// RollbackActive method rollback the history profile, then backup and active the current profile
-func (p *Profile) RollbackActive(ch chan *PB.AckCheck) error {
- if err := Rollback(); err != nil {
- return err
- }
-
- if err := p.Backup(); err != nil {
- return err
- }
-
- return p.active(ch)
-}
-
-func (p *Profile) active(ch chan *PB.AckCheck) error {
- if p.config == nil {
- return nil
- }
-
- if err := p.ItemSort(); err != nil {
- return err
- }
-
- //when active profile, make sure the output in the same order
- var itemKeys []string
- for item := range p.items {
- itemKeys = append(itemKeys, item)
- }
- sort.Strings(itemKeys)
-
- for _, item := range itemKeys {
- value := p.items[item]
- for _, section := range value.Sections() {
- if section.Name() == "main" {
- continue
- }
- if section.Name() == "DEFAULT" {
- continue
- }
-
- for _, key := range section.Keys() {
- scriptKey := key.Name()
- scriptKey, err := p.replaceParameter(scriptKey)
- if err != nil {
- return err
- }
- value, err := p.replaceParameter(key.Value())
- if err != nil {
- return err
- }
- if section.Name() == "script" {
- scriptKey = path.Join(config.DefaultScriptPath, strings.Trim(key.Name(), " "))
- }
-
- if section.HasKey(scriptKey) {
- key.SetValue(value)
- continue
- }
- section.NewKey(scriptKey, value)
- section.DeleteKey(key.Name())
- }
- }
- }
-
- scheduler := schedule.GetScheduler()
- scheduler.Active(ch, itemKeys, p.items)
- p.Save()
-
- return nil
-}
-
-// Save method set the workload type of Profile to active state
-func (p *Profile) Save() error {
- return sqlstore.ActiveProfile(p.name)
-}
-
-// SetWorkloadType method set the workload type name to Profile
-func (p *Profile) SetWorkloadType(name string) {
- p.name = name
-}
-
-//ItemSort method allocate property to diffrent item
-func (p *Profile) ItemSort() error {
- if p.config == nil {
- return nil
- }
- p.items = make(map[string]*ini.File)
- var itemName string
- for _, section := range p.config.Sections() {
- for _, key := range section.Keys() {
- if section.Name() == "main" {
- continue
- }
- if section.Name() == "DEFAULT" {
- continue
- }
- if section.Name() == "inputs" {
- continue
- }
- if section.Name() == "tip" {
- if key.Value() == "warning" {
- itemName = "SUGGEST"
- } else {
- itemName = "REQUEST"
- }
- } else {
- itemQuery, err := sqlstore.GetPropertyItem(key.Name())
- if err != nil {
- log.Errorf("key %s is not exist in tuned_item", key.Name())
- itemName = "OTHERS"
- } else {
- itemName = itemQuery
- }
- }
-
- if _, ok := p.items[itemName]; !ok {
- p.items[itemName] = ini.Empty()
- }
- if itemSection := p.items[itemName].Section(section.Name()); itemSection == nil {
- p.items[itemName].NewSection(section.Name())
- }
- itemSection, _ := p.items[itemName].GetSection(section.Name())
- itemSection.NewKey(key.Name(), key.Value())
- }
- }
- return nil
-}
-
-// Check method check wether the actived profile is effective
-func (p *Profile) Check(ch chan *PB.AckCheck) error {
- if p.config == nil {
- return nil
- }
-
- for _, section := range p.config.Sections() {
- if section.Name() == "main" {
- continue
- }
- if section.Name() == "DEFAULT" {
- continue
- }
- if section.Name() == "tip" {
- continue
- }
-
- var statusStr = "OK"
- for _, key := range section.Keys() {
- scriptKey := key.Name()
- scriptKey, err := p.replaceParameter(scriptKey)
- if err != nil {
- return err
- }
-
- value, err := p.replaceParameter(key.Value())
- if err != nil {
- return err
- }
-
- if section.Name() == "script" {
- scriptKey = path.Join(config.DefaultScriptPath, strings.Trim(key.Name(), " "))
- }
-
- body := &ConfigPutBody{
- Section: section.Name(),
- Key: scriptKey,
- Value: value,
- }
-
- respPutIns, err := body.Get()
- if err != nil {
- sendChanToAdm(ch, key.Name(), utils.FAILD, err.Error())
- continue
- }
-
- statusStr = respPutIns.Status
-
- statusStr = strings.ToUpper(statusStr)
- if statusStr == "OK" {
- description := fmt.Sprintf("value: %s", value)
- sendChanToAdm(ch, key.Name(), utils.SUCCESS, description)
- } else if statusStr == "UNKNOWN" {
- description := fmt.Sprintf("expext value: %s, real value: %s", value, statusStr)
- sendChanToAdm(ch, key.Name(), utils.WARNING, description)
- } else {
- description := fmt.Sprintf("expext value: %s, real value: %s", value, statusStr)
- sendChanToAdm(ch, key.Name(), utils.FAILD, description)
- }
- }
- }
-
- return nil
-}
-
-// ActiveTuned method set the profile that dynamic tuned matched
-func (p *Profile) ActiveTuned(ch chan *PB.AckCheck, params string) error {
- if p.config == nil {
- return nil
- }
-
- tuned := make(map[string]string)
- paramTuned := strings.Split(params, ",")
- for _, param := range paramTuned {
- value := strings.Split(param, "=")
- if len(value) != 2 {
- continue
- }
- tuned[value[0]] = value[1]
- }
-
- for _, section := range p.config.Sections() {
- if section.Name() == "main" {
- continue
- }
- if section.Name() == "DEFAULT" {
- continue
- }
- if section.Name() == "tip" {
- continue
- }
-
- var statusStr = "OK"
- for _, key := range section.Keys() {
- scriptKey := key.Name()
- if section.Name() == "script" {
- scriptKey = path.Join(config.DefaultScriptPath, strings.Trim(key.Name(), " "))
- }
- if _, exist := tuned[key.Name()]; !exist {
- continue
- }
-
- body := &ConfigPutBody{
- Section: section.Name(),
- Key: scriptKey,
- Value: tuned[key.Name()],
- }
-
- respPutIns, err := body.Put()
- if err != nil {
- sendChanToAdm(ch, key.Name(), utils.FAILD, err.Error())
- continue
- }
-
- log.Infof("active parameter, key: %s, value: %s, status:%s", scriptKey, key.Value(), respPutIns.Status)
- statusStr = respPutIns.Status
-
- statusStr = strings.ToUpper(statusStr)
- if statusStr == "OK" {
- description := fmt.Sprintf("value: %s", key.Value())
- sendChanToAdm(ch, key.Name(), utils.SUCCESS, description)
- } else if statusStr == "UNKNOWN" {
- description := fmt.Sprintf("expext value: %s, real value: %s", key.Value(), statusStr)
- sendChanToAdm(ch, key.Name(), utils.WARNING, description)
- } else {
- description := fmt.Sprintf("expext value: %s, real value: %s", key.Value(), statusStr)
- sendChanToAdm(ch, key.Name(), utils.FAILD, description)
- }
- }
- }
-
- return nil
-}
-
-func sendChanToAdm(ch chan *PB.AckCheck, item string, status string, description string) {
- if ch == nil {
- return
- }
-
- ch <- &PB.AckCheck{Name: item, Status: status, Description: description}
-}
-
-func (p *Profile) replaceParameter(str string) (string, error) {
- re := regexp.MustCompile(`\{([^}]+)\}`)
- matches := re.FindAllStringSubmatch(str, -1)
- if len(matches) > 0 {
- if p.inputs == nil {
- return str, fmt.Errorf("input section is not exist")
- }
- for _, match := range matches {
- if !p.inputs.Haskey(match[1]) {
- return str, fmt.Errorf("%s is not exist int the inputs section", match[1])
- }
- value := p.inputs.Key(match[1]).Value()
- str = re.ReplaceAllString(str, value)
- }
- }
- return str, nil
-}
diff --git a/common/profile/profile_rollback.go b/common/profile/profile_rollback.go
deleted file mode 100644
index 7694c5b..0000000
--- a/common/profile/profile_rollback.go
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/log"
- "atune/common/models"
- "atune/common/sqlstore"
- "atune/common/utils"
- "fmt"
- "os"
- "sort"
- "strings"
-
- "github.com/go-ini/ini"
-)
-
-// HistoryProfile :load profile history type
-type HistoryProfile struct {
- name string
-
- config *ini.File
-}
-
-// Resume method set the system state to the time before setting ProfileLog.
-func (p *HistoryProfile) Resume(ch chan *PB.AckCheck) error {
- for _, section := range p.config.Sections() {
- sectionKeys := section.KeyStrings()
- for index := len(sectionKeys) - 1; index >= 0; index-- {
- key := section.Key(sectionKeys[index])
- body := &models.Profile{
- Section: section.Name(),
- Config: key.Value(),
- }
-
- respPutIns, err := body.Resume()
- if err != nil {
- description := fmt.Sprintf("key: %s, resume failed: %v", key.Name(), err.Error())
- log.Errorf(description)
- sendChanToAdm(ch, key.Name(), utils.FAILD, description)
- continue
- }
-
- statusStr := respPutIns.Status
- statusStr = strings.ToUpper(statusStr)
- if statusStr == "OK" {
- description := fmt.Sprintf("value: %s", key.Value())
- sendChanToAdm(ch, key.Name(), utils.SUCCESS, description)
- } else {
- description := fmt.Sprintf("faild: %s", statusStr)
- sendChanToAdm(ch, key.Name(), utils.FAILD, description)
- }
- }
-
- }
-
- return nil
-}
-
-// Load method load the context to config field
-func (p *HistoryProfile) Load(context string) error {
- config, err := ini.Load([]byte(context))
- if err != nil {
- return err
- }
- p.config = config
- return nil
-}
-
-// Rollback methed reset profile to system init state
-func Rollback() error {
- profileLogs, err := sqlstore.GetProfileLogs()
- if err != nil {
- log.Errorf("get profile history faild, %v", err)
- return err
- }
-
- if len(profileLogs) < 1 {
- return nil
- }
-
- sort.Slice(profileLogs, func(i, j int) bool {
- return profileLogs[i].ID > profileLogs[j].ID
- })
-
- for _, pro := range profileLogs {
- log.Infof("begin to restore profile id: %s", pro.ID)
- profileInfo := HistoryProfile{}
- profileInfo.Load(pro.Context)
- profileInfo.Resume(nil)
-
- // delete profile log after restored
- if err := sqlstore.DelProfileLogByID(pro.ID); err != nil {
- return err
- }
- //delete backup dir
- if err := os.RemoveAll(pro.BackupPath); err != nil {
- return err
- }
- }
- if err := sqlstore.InActiveProfile(); err != nil {
- return nil
- }
-
- return nil
-}
diff --git a/common/project/projet.go b/common/project/projet.go
deleted file mode 100644
index bba850c..0000000
--- a/common/project/projet.go
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package project
-
-import (
- "atune/common/log"
- "atune/common/utils"
- "fmt"
- "io/ioutil"
- "os/exec"
- "strconv"
- "strings"
-
- yaml "gopkg.in/yaml.v2"
-)
-
-// Evaluate :store the evaluate object
-type Evaluate struct {
- Name string `yaml : "name"`
- Info EvalInfo `yaml : "info"`
-}
-
-// EvalInfo :store the evaluation object
-type EvalInfo struct {
- Get string `yaml : "get"`
- Type string `yaml : "type"`
- Weight int64 `yaml : "weight"`
- Threshold int64 `yaml : "threshold"`
-}
-
-// YamlPrj :store the yaml project
-type YamlPrj struct {
- Object []YamlPrjObj `yaml : "object"`
- Startworkload string `yaml : "startworkload"`
- Stopworkload string `yaml : "stopworkload"`
- Iterations int `yaml : "iterations"`
- Benchmark string `yaml : "benchmark"`
- Evaluations []Evaluate `yaml : "evaluations"`
-}
-
-// YamlObj :yaml Object
-type YamlObj struct {
- Name string `yaml:"name"`
- Desc string `yaml:"desc"`
- GetScript string `yaml:"get"`
- SetScript string `yaml:"set"`
- Needrestart string `yaml:"needrestart"`
- Type string `yaml:"type"`
- Step int64 `yaml:"step"`
- Items []int64 `yaml:"items"`
- Options []string `yaml:"options"`
- Scope []int64 `yaml:"scope,flow"`
- Dtype string `yaml:"dtype"`
- Ref string `yaml:"ref"`
-}
-
-// YamlPrjObj :store the yaml object
-type YamlPrjObj struct {
- Name string `yaml : "name"`
- Info YamlObj `yaml : "info"`
-}
-
-// LoadProject method load the tuning yaml
-func LoadProject(path string) (*YamlPrj, error) {
- exist, err := utils.PathExist(path)
- if err != nil {
- return nil, err
- }
-
- if !exist {
- return nil, fmt.Errorf("The path %s doesn't exist", path)
- }
-
- return newProject(path)
-}
-
-func newProject(path string) (*YamlPrj, error) {
- info, err := ioutil.ReadFile(path)
- if err != nil {
- return nil, err
- }
-
- prj := new(YamlPrj)
- if err := yaml.Unmarshal(info, prj); err != nil {
- return nil, fmt.Errorf("Parse %s failed : %s", path, err)
- }
-
- return prj, nil
-}
-
-// BenchMark method call the benchmark script
-func (y *YamlPrj) BenchMark() ([]byte, error) {
- log.Info("start to benchmark the performance")
- cmd := exec.Command("sudo", "sh", "-c", y.Benchmark)
- benchOutByte, err := cmd.CombinedOutput()
-
- if err != nil {
- return nil, err
- }
- return benchOutByte, nil
-}
-
-// Evaluation method get the evaluation value from the benchmark result
-func (y *YamlPrj) Evaluation(benchmarkByte []byte) (string, error) {
- benchmarkOut := string(benchmarkByte)
-
- benchStr := ""
- for _, evaluation := range y.Evaluations {
- newScript := strings.Replace(evaluation.Info.Get, "$out", benchmarkOut, -1)
- cmd := exec.Command("sudo", "sh", "-c", newScript)
- bout, err := cmd.Output()
- if err != nil {
- log.Error(err)
- return benchStr, err
- }
- floatout, err := strconv.ParseFloat(strings.Replace(string(bout), "\n", "", -1), 64)
- if err != nil {
- log.Error(err)
- return benchStr, err
- }
-
- out := strconv.FormatFloat((floatout * float64(evaluation.Info.Weight) / 100), 'E', -1, 64)
- if evaluation.Info.Type == "negative" {
- out = "-" + out
- }
- benchStr = benchStr + out + ","
- }
- benchStr = benchStr[:len(benchStr)-1]
- return benchStr, nil
-}
-
-// RunSet method call the set script to set set the value
-func (y *YamlPrj) RunSet(optStr string) error {
- paraMap := make(map[string]string)
- paraSlice := strings.Split(optStr, ",")
- for _, para := range paraSlice {
- kvs := strings.Split(para, "=")
- paraMap[kvs[0]] = kvs[1]
- }
- for _, obj := range y.Object {
- obj.Info.Ref = paraMap[obj.Name]
- }
-
- for _, obj := range y.Object {
- script := obj.Info.SetScript
- newScript := strings.Replace(script, "$value", obj.Info.Ref, -1)
- log.Info("set script:", newScript)
- cmd := exec.Command("sudo", "sh", "-c", newScript)
- err := cmd.Run()
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// RestartProject method call the StartWorkload and StopWorkload script to restart the service
-func (y *YamlPrj) RestartProject() error {
- startWorkload := y.Startworkload
- stopWorkload := y.Stopworkload
-
- needRestart := false
- for _, obj := range y.Object {
- if obj.Info.Needrestart == "true" {
- needRestart = true
- break
- }
- }
- if needRestart == true {
- cmd := exec.Command("sudo", "sh", "-c", stopWorkload)
- out, err := cmd.CombinedOutput()
- log.Debug(string(out))
-
- if err != nil {
- return err
- }
-
- cmd = exec.Command("sudo", "sh", "-c", startWorkload)
- out, err = cmd.CombinedOutput()
- log.Debug(string(out))
-
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/common/registry/register.go b/common/registry/register.go
deleted file mode 100644
index c6bb14c..0000000
--- a/common/registry/register.go
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package registry
-
-import (
- "atune/common/config"
-)
-
-// DaemonInstance :interface for Daemon service
-type DaemonInstance interface {
- Init() error
- Set(cfg *config.Cfg)
-}
-
-// DaemonService :registry for the daemon service
-type DaemonService struct {
- Name string
- Instance DaemonInstance
-}
-
-var daemonServices []*DaemonService
-
-// RegisterDaemonService method add service to damonService slice
-func RegisterDaemonService(name string, instance DaemonInstance) {
- daemonServices = append(daemonServices, &DaemonService{
- Name: name,
- Instance: instance,
- })
-}
-
-// GetDaemonServices method return the service slice
-func GetDaemonServices() []*DaemonService {
- return daemonServices
-}
-
-// BackgroundService : the interface of the background service
-type BackgroundService interface {
- Run() error
-}
diff --git a/common/schedule/filter.go b/common/schedule/filter.go
deleted file mode 100644
index 0ce7683..0000000
--- a/common/schedule/filter.go
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package schedule
-
-import (
- "atune/common/schedule/filters"
-)
-
-type ScheduleFilter interface {
- Filte(strategy string) error
-}
-
-func Factory(name string) ScheduleFilter {
- switch name {
- case "irq":
- return &filters.IrqSchedule{Name: "irq"}
- case "numa":
- return &filters.NumaSchedule{Name: "numa"}
- case "cpu":
- return &filters.CpuSchedule{Name: "cpu"}
- default:
- return nil
- }
-}
diff --git a/common/schedule/filters/cpu.go b/common/schedule/filters/cpu.go
deleted file mode 100644
index d558178..0000000
--- a/common/schedule/filters/cpu.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package filters
-
-import (
- "atune/common/log"
- "atune/common/system"
- "errors"
-)
-
-type CpuSchedule struct {
- Name string
-}
-
-func (s *CpuSchedule) Filte(strategy string) error {
- switch strategy {
- case "auto":
- case "performance":
- return s.performance()
- case "powersave":
- return s.powersave()
- default:
- return errors.New("Strategy don't exist")
- }
- return nil
-}
-
-func (s *CpuSchedule) performance() error {
- system := system.GetSystem()
-
- for _, pid := range system.GetPids("") {
- log.Infof("pid: %d", pid)
- }
-
- return nil
-}
-
-func (s *CpuSchedule) powersave() error {
- system := system.GetSystem()
-
- for _, pid := range system.GetPids("") {
- log.Infof("pid: %d", pid)
- }
-
- return nil
-}
diff --git a/common/schedule/filters/irq.go b/common/schedule/filters/irq.go
deleted file mode 100644
index 37bbb2d..0000000
--- a/common/schedule/filters/irq.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package filters
-
-import (
- "atune/common/log"
- "atune/common/system"
- "errors"
-)
-
-type IrqSchedule struct {
- Name string
-}
-
-func (s *IrqSchedule) Filte(strategy string) error {
- switch strategy {
- case "performance":
- case "auto":
- return s.performance()
- case "powersave":
- return s.powersave()
- default:
- return errors.New("Strategy don't exist")
- }
- return nil
-}
-
-func (s *IrqSchedule) performance() error {
- system := system.GetSystem()
-
- for _, irq := range system.GetAllIrq() {
- log.Infof("irq: %d", irq)
- }
-
- return nil
-}
-
-func (s *IrqSchedule) powersave() error {
- system := system.GetSystem()
-
- for _, irq := range system.GetAllIrq() {
- log.Infof("irq: %d", irq)
- }
-
- return nil
-}
diff --git a/common/schedule/filters/numa.go b/common/schedule/filters/numa.go
deleted file mode 100644
index 2092dc2..0000000
--- a/common/schedule/filters/numa.go
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package filters
-
-import (
- "atune/common/log"
- "atune/common/system"
- "errors"
-)
-
-type NumaSchedule struct {
- Name string
-}
-
-func (s *NumaSchedule) Filte(strategy string) error {
- switch strategy {
- case "performance":
- case "auto":
- return s.performance()
- case "powersave":
- return s.powersave()
- default:
- return errors.New("Strategy don't exist")
- }
- return nil
-}
-
-func (s *NumaSchedule) performance() error {
- system := system.GetSystem()
-
- for _, numa := range system.GetNuma() {
- log.Infof("numa: %d", numa)
- }
-
- return nil
-}
-
-func (s *NumaSchedule) powersave() error {
- system := system.GetSystem()
-
- for _, numa := range system.GetNuma() {
- log.Infof("numa: %d", numa)
- }
-
- return nil
-}
diff --git a/common/schedule/schedule.go b/common/schedule/schedule.go
deleted file mode 100644
index e615d63..0000000
--- a/common/schedule/schedule.go
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package schedule
-
-import (
- PB "atune/api/profile"
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "atune/common/sqlstore"
- "atune/common/utils"
- "encoding/json"
- "errors"
- "fmt"
- "io/ioutil"
- "strings"
-
- "github.com/go-ini/ini"
-)
-
-func sendChanToAdm(ch chan *PB.AckCheck, item string, status string, description string) {
- if ch == nil {
- return
- }
-
- ch <- &PB.AckCheck{Name: item, Status: status, Description: description}
-}
-
-type ConfigPutBody struct {
- Section string `json:"section"`
- Key string `json:"key"`
- Value string `json:"value"`
-}
-
-type respPut struct {
- Status string `json:status`
- Value string `json:value`
-}
-
-func (c *ConfigPutBody) Put() (*respPut, error) {
- url := config.GetUrl(config.ConfiguratorURI)
- res, err := http.Put(url, c)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("connect to configurator service faild")
- }
- resBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(respPut)
- err = json.Unmarshal(resBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-
-}
-
-func (c *ConfigPutBody) Get() (*respPut, error) {
- url := config.GetUrl(config.ConfiguratorURI)
- res, err := http.Get(url, c)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("connect to configurator service faild")
- }
- resBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(respPut)
- err = json.Unmarshal(resBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-
-}
-
-type Scheduler struct {
- schedule []*sqlstore.Schedule
- name string
-
- typename string
- strategy string
- IsExit bool
-}
-
-var instance *Scheduler = nil
-
-func (s *Scheduler) Init() error {
- s.schedule = sqlstore.GetSchedule()
-
- return nil
-}
-
-func (s *Scheduler) Schedule(typename string, strategy string, save bool) error {
- if save {
- sqlstore.UpdateSchedule(typename, strategy)
-
- s.schedule = sqlstore.GetSchedule()
- for _, item := range s.schedule {
- s.DoSchedule(item.Type, item.Strategy)
- }
- } else {
- s.DoSchedule(typename, strategy)
- }
-
- return nil
-}
-
-func (s *Scheduler) DoSchedule(typename string, strategy string) error {
- filter := Factory(typename)
- if filter == nil {
- return errors.New("type don't exist")
- }
-
- return filter.Filte(strategy)
-}
-
-func (s *Scheduler) Active(ch chan *PB.AckCheck, itemKeys []string, items map[string]*ini.File) error {
- for _, item := range itemKeys {
- value := items[item]
- for _, section := range value.Sections() {
- if section.Name() == "main" {
- continue
- }
- if section.Name() == "DEFAULT" {
- continue
- }
- if section.Name() == "tip" {
- for _, key := range section.Keys() {
- description := fmt.Sprintf("%s", key.Name())
- if key.Value() == "error" {
- sendChanToAdm(ch, item, utils.REQUEST, description)
- } else {
- sendChanToAdm(ch, item, utils.WARNING, description)
- }
- }
- continue
- }
- if section.Name() == "schedule" {
- for _, key := range section.Keys() {
- s.Schedule(key.Name(), key.Value(), false)
- }
- continue
- }
-
- var statusStr string = "OK"
- message := make([]string, 0)
- for _, key := range section.Keys() {
- scriptKey := key.Name()
- value := key.Value()
- body := &ConfigPutBody{
- Section: section.Name(),
- Key: scriptKey,
- Value: value,
- }
- respPutIns, err := body.Put()
- if err != nil {
- statusStr = err.Error()
- continue
- }
-
- log.Infof("active parameter, key: %s, value: %s, status:%s", scriptKey, value, respPutIns.Status)
- if respPutIns.Status == "OK" {
- message = append(message, scriptKey)
- } else {
- if statusStr != "ERROR" {
- statusStr = respPutIns.Status
- }
- message = append(message, respPutIns.Value)
- }
- }
-
- message = utils.RemoveDuplicateElement(message)
- status := strings.ToUpper(statusStr)
- if status == "OK" {
- sendChanToAdm(ch, item, utils.SUCCESS, strings.Join(message, ","))
- } else if status == "WARNING" {
- sendChanToAdm(ch, item, utils.REQUEST, strings.Join(message, ","))
- } else {
- sendChanToAdm(ch, item, utils.FAILD, strings.Join(message, ","))
- }
- }
- }
-
- return nil
-}
-
-func GetScheduler() *Scheduler {
- if instance == nil {
- instance = new(Scheduler)
- instance.Init()
- }
-
- return instance
-}
diff --git a/common/service/monitor/monitor.go b/common/service/monitor/monitor.go
deleted file mode 100644
index bd85ffc..0000000
--- a/common/service/monitor/monitor.go
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package monitors
-
-import (
- "atune/common/config"
- HTTP "atune/common/http"
- "atune/common/log"
- "atune/common/profile"
- "atune/common/registry"
- "atune/common/sqlstore"
- "atune/common/utils"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "strings"
-)
-
-func init() {
- registry.RegisterDaemonService("monitor", &Monitor{})
-}
-
-// Monitor : the struct store the monitor service conf message
-type Monitor struct {
- Cfg *config.Cfg
-}
-
-// Init method
-func (m *Monitor) Init() error {
- return nil
-}
-
-// Set the config of the monitor
-func (m *Monitor) Set(cfg *config.Cfg) {
- m.Cfg = cfg
-}
-
-// MonitorBody :the body send to monitor service
-type MonitorBody struct {
- Module string `json:"module"`
- Purpose string `json:"purpose"`
- Fmt string `json:"fmt"`
- Path string `json:"path"`
- Para string `json:"para"`
-}
-
-// RespBody :the response of the monitor service
-type RespBody struct {
- Status string `json:"status"`
-}
-
-// Get method calling the get method of the monitor service
-func (m *MonitorBody) Get() (*RespBody, error) {
- url := config.GetUrl(config.MonitorURI)
- res, err := HTTP.Get(url, m)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- if res.StatusCode != 200 {
- return nil, fmt.Errorf("connect to monitor service faild")
- }
- resBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(RespBody)
- err = json.Unmarshal(resBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-}
-
-// Run method start the monitor service
-func (m *Monitor) Run() error {
- if err := utils.WaitForPyservice(); err != nil {
- log.Errorf("waiting for pyservice faild: %v", err)
- return err
- }
-
- if err := activeProfile(); err != nil {
- return err
- }
-
- monitorModules := strings.Split(m.Cfg.Raw.Section("monitor").Key("module").String(), ",")
- monitorPath := config.DefaultCheckerPath
-
- exist, err := utils.PathExist(monitorPath)
- if err != nil {
- return err
- }
-
- if !exist {
- os.MkdirAll(monitorPath, os.ModePerm)
- }
-
- for _, module := range monitorModules {
- module = strings.TrimSpace(module)
- modulePurpose := strings.Split(module, "_")
- if len(modulePurpose) != 2 {
- log.Errorf("module format %s is not corrent!")
- continue
- }
-
- filename := module + "." + config.FileFormat
- filename = path.Join(monitorPath, filename)
-
- monitorBody := &MonitorBody{
- Module: strings.ToUpper(modulePurpose[0]),
- Purpose: strings.ToUpper(modulePurpose[1]),
- Fmt: config.FileFormat,
- Path: filename,
- }
-
- respGetIns, err := monitorBody.Get()
- if err != nil {
- log.Errorf("collect module %s faild", module)
- continue
- }
-
- if respGetIns.Status != "OK" {
- log.Errorf("collect module %s faild, error: %s", module, respGetIns.Status)
- continue
- }
- }
- return nil
-}
-
-func activeProfile() error {
- // Load Current Active Profile
- profiles := &sqlstore.GetClass{Active: true}
- err := sqlstore.GetClasses(profiles)
- if err != nil {
- return err
- }
- if len(profiles.Result) != 1 {
- return fmt.Errorf("No active profile or more than 1 active profile")
- }
-
- //profile_names := strings.Split(strings.Trim(profiles.Result[0].ProfileType, "\n"), " ")
- profileType := profiles.Result[0].Class
- pro, _ := profile.LoadFromWorkloadType(profileType)
- pro.RollbackActive(nil)
-
- return nil
-}
diff --git a/common/service/pyservice/pyservice.go b/common/service/pyservice/pyservice.go
deleted file mode 100644
index 0f673a6..0000000
--- a/common/service/pyservice/pyservice.go
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package pyservice
-
-import (
- "atune/common/config"
- "atune/common/log"
- "atune/common/registry"
- "bufio"
- "fmt"
- "io"
- "os"
- "os/exec"
- "os/signal"
- "path"
- "strings"
- "syscall"
-)
-
-func init() {
- registry.RegisterDaemonService("pyengine", &PyEngine{})
-}
-
-// PyEngine : the struct store the pyEngine conf
-type PyEngine struct {
- Cfg *config.Cfg
-}
-
-// Init method init the PyEngine service
-func (p *PyEngine) Init() error {
- return nil
-}
-
-// Set the config of the monitor
-func (p *PyEngine) Set(cfg *config.Cfg) {
- p.Cfg = cfg
-}
-
-// Run method start the python service
-func (p *PyEngine) Run() error {
- cmdSlice := make([]string, 0)
- cmdSlice = append(cmdSlice, "python3")
- cmdSlice = append(cmdSlice, path.Join(config.DefaultAnalysisPath, "app.py"))
- cmdSlice = append(cmdSlice, path.Join(config.DefaultConfPath, "atuned.cnf"))
-
- cmdStr := strings.Join(cmdSlice, " ")
- cmd := exec.Command("sh", "-c", cmdStr)
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
-
- stdout, err := cmd.StdoutPipe()
- stderr, err := cmd.StderrPipe()
-
- go listenToSystemSignals(cmd)
-
- go logStdout(stdout)
- go logStderr(stderr)
- err = cmd.Start()
- if err != nil {
- return fmt.Errorf("cmd.Start() analysis service faild: %v", err)
- os.Exit(-1)
- }
-
- err = cmd.Wait()
-
- if err != nil {
- log.Errorf("cmd.Run() analysis faild with: %v", err)
- os.Exit(-1)
- }
-
- return nil
-
-}
-
-func logStdout(stdout io.ReadCloser) {
- scanner := bufio.NewScanner(stdout)
- for scanner.Scan() {
- line := scanner.Text()
- log.Debug(line)
- }
-}
-
-func logStderr(stderr io.ReadCloser) {
- scanner := bufio.NewScanner(stderr)
- for scanner.Scan() {
- line := scanner.Text()
- log.Debug(line)
- }
-}
-
-func listenToSystemSignals(cmd *exec.Cmd) {
- signalChan := make(chan os.Signal, 1)
-
- signal.Notify(signalChan, os.Interrupt, os.Kill, syscall.SIGKILL)
- select {
- case <-signalChan:
- syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
- os.Exit(-1)
- }
-}
diff --git a/common/service/service.go b/common/service/service.go
deleted file mode 100644
index f39ca38..0000000
--- a/common/service/service.go
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package module
-
-import (
- "fmt"
- "sync"
-
- "github.com/urfave/cli"
- "google.golang.org/grpc"
-)
-
-// OptServices :the global value to store grpc service
-var OptServices = struct {
- sync.RWMutex
- services map[string]*ProfileService
-}{}
-
-func init() {
- OptServices.services = make(map[string]*ProfileService)
-}
-
-// ProfileService :the service for grpc server
-type ProfileService struct {
- Name string
- Requires []string
- Desc string
- Path string
- NewInst func(ctx *cli.Context, opts ...interface{}) (interface{}, error)
-}
-
-func (s *ProfileService) String() string {
- return s.Name
-}
-
-// SvrService :every service need to implement SvrService and CliService interface.
-// one for server side, the other is for client side
-type SvrService interface {
- RegisterServer(*grpc.Server) error
- Healthy(opts ...interface{}) error
-}
-
-// CliService :the interface for grpc client
-type CliService interface {
- Register() error
- GetCommand() cli.Command
-}
-
-// AddService method register the service svc
-func AddService(svc *ProfileService) error {
- OptServices.Lock()
- defer OptServices.Unlock()
-
- if _, existed := OptServices.services[svc.Name]; existed {
- return fmt.Errorf("service existed : %s", svc.Name)
- }
-
- OptServices.services[svc.Name] = svc
-
- return nil
-}
-
-// WalkServices method callback the fn method
-func WalkServices(fn func(nm string, svc *ProfileService) error) error {
- OptServices.Lock()
- defer OptServices.Unlock()
-
- for name, service := range OptServices.services {
- if err := fn(name, service); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// CreateInstance method return the instance of service of name
-func CreateInstance(name string) (interface{}, error) {
- OptServices.Lock()
- defer OptServices.Unlock()
-
- svc, existed := OptServices.services[name]
- if !existed {
- return nil, fmt.Errorf("There is not %s service", name)
- }
-
- instance, err := svc.NewInst(nil)
- if err != nil {
- return nil, err
- }
-
- return instance, nil
-}
-
-// GetServices return the slice of the service name
-func GetServices() ([]string, error) {
- OptServices.Lock()
- defer OptServices.Unlock()
-
- var svc []string
- for name := range OptServices.services {
- svc = append(svc, name)
- }
-
- return svc, nil
-}
diff --git a/common/service/timer/timer.go b/common/service/timer/timer.go
deleted file mode 100644
index 496ac82..0000000
--- a/common/service/timer/timer.go
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package timer
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- "atune/common/config"
- "atune/common/log"
- "atune/common/utils"
- "fmt"
- "io"
- "strconv"
- "time"
-
- CTX "golang.org/x/net/context"
-)
-
-func init() {
- // registry.RegisterDaemonService("timer", &Timer{})
-}
-
-// Timer : a timer for dynamic tuning
-type Timer struct {
- Cfg *config.Cfg
- ticker *time.Ticker
- interval int
- isRun bool
-}
-
-// Init method init the Timer service
-func (t *Timer) Init() error {
- t.interval = 60
- return nil
-}
-
-// Set the config of the monitor
-func (t *Timer) Set(cfg *config.Cfg) {
- t.Cfg = cfg
-}
-
-//Run method start the ticker, auto-tuning the system
-func (t *Timer) Run() error {
- /* Static & Dynamic judge */
- if err := utils.WaitForPyservice(); err != nil {
- log.Errorf("waiting for pyservice faild: %v", err)
- return err
- }
-
- section, err := t.Cfg.Raw.GetSection("server")
- if err != nil {
- log.Errorf("Faild to get section system, error: %v", err)
- return err
- }
- if !section.Haskey("type") {
- return fmt.Errorf("type is not exist in the server section")
- }
-
- if section.Key("type").Value() == "static" {
- return nil
- } else if section.Key("type").Value() == "dynamic" {
- if section.Haskey("interval") {
- t.interval, _ = section.Key("interval").Int()
- }
-
- d, _ := time.ParseDuration(strconv.FormatInt(int64(t.interval), 10) + "s")
- t.ticker = time.NewTicker(d)
- t.isRun = true
-
- c, err := client.NewClientWithoutCli(config.DefaultTgtAddr, config.DefaultTgtPort)
- if err != nil {
- return err
- }
- defer c.Close()
-
- for {
- <-t.ticker.C
- log.Info("active the ticker, starting dynamic tuning,")
- go func() error {
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Analysis(CTX.Background(), &PB.AnalysisMessage{})
- if err != nil {
- log.Error(err)
- return err
- }
- for {
- _, err := stream.Recv()
- if err == io.EOF {
- break
- }
-
- if err != nil {
- log.Error(err)
- return err
- }
- }
- return nil
- }()
- }
- } else {
- return fmt.Errorf("in section server, type must be dynamic or statis")
- }
-
- return nil
-}
diff --git a/common/sqlstore/models.go b/common/sqlstore/models.go
deleted file mode 100644
index 19e94f9..0000000
--- a/common/sqlstore/models.go
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package sqlstore
-
-import (
- "errors"
- "time"
-)
-
-var (
- // ErrServiceNotFound : error message
- ErrServiceNotFound = errors.New("service not fount")
-)
-
-// ClassApps : table class_apps
-type ClassApps struct {
- Class string `xorm:"class"`
- Apps string `xorm:"apps"`
- ResourceLimit string `xorm:"resource_limit"`
- Deletable bool `xorm:"deletable"`
-}
-
-// ClassProfile : table class_profile
-type ClassProfile struct {
- Class string `xorm:"class"`
- ProfileType string `xorm:"profile_type"`
- Active bool `xorm:"active"`
-}
-
-// Profile : table profile
-type Profile struct {
- ProfileType string `xorm:"profile_type"`
- ProfileInformation string `xorm:"profile_information"`
-}
-
-// Tuned : table tuned
-type Tuned struct {
- ID int64 `xorm:"id"`
- Class string `xorm:"class"`
- Name string `xorm:"name"`
- Type string `xorm:"type"`
- Value string `xorm:"value"`
- Range string `xorm:"range"`
- Step int64 `xorm:"step"`
-}
-
-// RuleTuned : table rule_tuned
-type RuleTuned struct {
- ID int64 `xorm:"id"`
- Name string `xorm;"name"`
- Class string `xorm;"class"`
- Expression string `xorm:"expression"`
- Action string `xorm:"action"`
- OppositeAction string `xorm:"opposite_action"`
- Monitor string `xorm:"monitor"`
- Field string `xorm:"field"`
-}
-
-// Collection : table collection
-type Collection struct {
- ID int64 `xorm:"id"`
- Name string `xorm:"name"`
- Module string `xorm:"module"`
- Purpose string `xorm:"purpose"`
- Metrics string `xorm:"metrics"`
-}
-
-// ProfileLog : table profile_log
-type ProfileLog struct {
- ID int64 `xorm:"id"`
- ProfileID string `xorm:"profile_id"`
- Context string `xorm:"context"`
- BackupPath string `xorm:"backup_path"`
- Timestamp time.Time `xorm:"timestamp"`
-}
-
-type Schedule struct {
- Id int64 `xorm:"id"`
- Type string `xorm:"type"`
- Strategy string `xorm:"strategy"`
-}
-
-// GetClass : inquery the class_profile table
-type GetClass struct {
- Active bool
- Class string
- Result []*ClassProfile
-}
-
-// GetClassApp : inquery the class_apps table
-type GetClassApp struct {
- Class string
- Result []*ClassApps
-}
-
-// TunedItem : table tuned_item
-type TunedItem struct {
- ID int64 `xorm:"id"`
- Property string
- Item string
-}
-
-// GetTuned : inquery the tuned for bayes search
-type GetTuned struct {
- ID int64
- Class string
- Result []*Tuned
-}
-
-// GetRuleTuned : for inquery rules for tuned
-type GetRuleTuned struct {
- Class string
- Result []*RuleTuned
-}
-
-// GetProfileLog : for inquery profile_log table
-type GetProfileLog struct {
- ID int64
- Result []*ProfileLog
-}
diff --git a/common/sqlstore/service.go b/common/sqlstore/service.go
deleted file mode 100644
index cc4172c..0000000
--- a/common/sqlstore/service.go
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package sqlstore
-
-import (
- "atune/common/log"
- "errors"
- "strings"
-)
-
-// GetClasses method return item of table class_profile
-func GetClasses(query *GetClass) error {
- query.Result = make([]*ClassProfile, 0)
- session := globalEngine.Table("class_profile")
-
- if query.Class != "" {
- session.Where("class=?", query.Class)
- }
-
- if query.Active {
- session.Where("active=?", query.Active)
- }
-
- if err := session.Find(&query.Result); err != nil {
- return err
- }
-
- return nil
-}
-
-// InsertClassProfile method insert item to class_profile table
-func InsertClassProfile(value *ClassProfile) error {
- session := globalEngine.Table("class_profile")
- if _, err := session.Insert(value); err != nil {
- return err
- }
- return nil
-}
-
-// UpdateClassProfile method update the class_profile table
-func UpdateClassProfile(value *ClassProfile) error {
- session := globalEngine.Table("class_profile")
- if _, err := session.Where("class = ?", value.Class).Update(value); err != nil {
- return err
- }
- return nil
-}
-
-// DeleteClassProfile method delete item from class_profile table by workloadType
-func DeleteClassProfile(workloadType string) error {
- session := globalEngine.Table("class_profile")
- if _, err := session.Exec("delete from class_profile where class = ?", workloadType); err != nil {
- return err
- }
- return nil
-}
-
-// GetClassApps method return the item of table class_apps
-func GetClassApps(query *GetClassApp) error {
- query.Result = make([]*ClassApps, 0)
- session := globalEngine.Table("class_apps")
-
- if query.Class != "" {
- session.Where("class=?", query.Class)
- }
-
- if err := session.Find(&query.Result); err != nil {
- return err
- }
- return nil
-}
-
-// InsertClassApps method insert item to class_apps table
-func InsertClassApps(value *ClassApps) error {
- session := globalEngine.Table("class_apps")
- if _, err := session.Insert(value); err != nil {
- return err
- }
- return nil
-}
-
-// DeleteClassApps method delete item from class_apps table by workload type
-func DeleteClassApps(workloadType string) error {
- session := globalEngine.Table("class_apps")
- if _, err := session.Exec("delete from class_apps where class = ?", workloadType); err != nil {
- return err
- }
- return nil
-}
-
-// ExistWorkloadType method return true if workloadType exist otherwise return false
-func ExistWorkloadType(workloadType string) (bool, error) {
- session := globalEngine.Table("class_apps")
- exist, err := session.Where("class=?", workloadType).Exist()
-
- if err != nil {
- return false, err
- }
- return exist, nil
-}
-
-// GetContext method return the optimization item of workload type name
-func GetContext(name string) (string, error) {
- query := make([]*Profile, 0)
-
- session := globalEngine.Table("profile")
- if err := session.Where("profile_type=?", name).Find(&query); err != nil {
- return "", err
- }
-
- if len(query) != 1 {
- return "", errors.New("name not exist")
- }
-
- context := query[0].ProfileInformation
- return context, nil
-}
-
-// InsertProfile method insert self define profile to table profile
-func InsertProfile(value *Profile) error {
- session := globalEngine.Table("profile")
- session.Insert(value)
- return nil
-}
-
-// UpdateProfile method update the profile table
-func UpdateProfile(value *Profile) error {
- session := globalEngine.Table("profile")
- if _, err := session.Where("profile_type = ?", value.ProfileType).Update(value); err != nil {
- return err
- }
- return nil
-}
-
-// DeleteProfile method delete the item from profile table
-func DeleteProfile(profileType string) error {
- session := globalEngine.Table("profile")
- if _, err := session.Exec("delete from profile where profile_type = ?", profileType); err != nil {
- return err
- }
- return nil
-
-}
-
-// ExistProfile method return true if profileType exist otherwise return false
-func ExistProfile(profileType string) (bool, error) {
- session := globalEngine.Table("profile")
- exist, err := session.Where("profile_type=?", profileType).Exist()
-
- if err != nil {
- return false, err
- }
- return exist, nil
-}
-
-// ActiveProfile method set the workload type state to active
-func ActiveProfile(name string) error {
- session := globalEngine.Table("class_profile")
-
- name = strings.Trim(name, " ")
-
- profile := new(ClassProfile)
- session.Where("active=?", true).Get(profile)
-
- if profile.Class == name {
- return nil
- }
-
- session.Exec("update class_profile set active=? where class = ?", !profile.Active, profile.Class)
-
- newProfile := new(ClassProfile)
- has, err := session.Where("class=?", name).Get(newProfile)
- if err != nil {
- return err
- } else if !has {
- return errors.New("Profile does not exist")
- }
-
- session.Exec("update class_profile set active=? where class = ?", !newProfile.Active, newProfile.Class)
-
- return nil
-}
-
-// GetPropertyItem method return the classification of the specified property
-func GetPropertyItem(property string) (string, error) {
- tunedItem := new(TunedItem)
- session := globalEngine.Table("tuned_item")
- has, err := session.Where("property=?", property).Get(tunedItem)
- if err != nil {
- return "", err
- }
-
- if !has {
- return "", errors.New("property is not exist")
- }
-
- item := tunedItem.Item
-
- return item, nil
-}
-
-// GetProfileIDByName method return the profile history ID.
-// the parameter name is workload type
-func GetProfileIDByName(name string) (int64, error) {
- query := make([]*Profile, 0)
-
- session := globalEngine.Table("profile")
- if err := session.Where("name=?", name).Find(&query); err != nil {
- return -1, err
- }
-
- if len(query) != 1 {
- return -1, errors.New("profile name not exist")
- }
-
- //id := query[0].Id
- id := int64(0)
- return id, nil
-}
-
-// GetTuneds method return the dynamic tuned items which used for bayes search
-func GetTuneds(query *GetTuned) error {
- query.Result = make([]*Tuned, 0)
- session := globalEngine.Table("tuned")
-
- if query.Class != "" {
- session.Where("class=?", query.Class)
- }
-
- if err := session.Find(&query.Result); err != nil {
- return err
- }
-
- return nil
-}
-
-// GetRuleTuneds method return the rules inquery from rule_tuned table
-func GetRuleTuneds(query *GetRuleTuned) error {
- query.Result = make([]*RuleTuned, 0)
- session := globalEngine.Table("rule_tuned")
-
- if query.Class != "" {
- session.Where("class=?", query.Class)
- }
-
- if err := session.Find(&query.Result); err != nil {
- return err
- }
- return nil
-}
-
-// GetCollections method return the collection metrics
-func GetCollections() ([]*Collection, error) {
- collections := make([]*Collection, 0)
-
- session := globalEngine.Table("collection")
- if err := session.Find(&collections); err != nil {
- return nil, err
- }
-
- return collections, nil
-}
-
-// InsertProfileLog method insert profile history to database
-func InsertProfileLog(value *ProfileLog) error {
- session := globalEngine.Table("profile_log")
- session.Insert(value)
- return nil
-}
-
-// GetProfileLogs method return profile histories
-func GetProfileLogs() ([]*ProfileLog, error) {
- profileLogs := make([]*ProfileLog, 0)
-
- session := globalEngine.Table("profile_log")
- if err := session.Find(&profileLogs); err != nil {
- return nil, err
- }
- return profileLogs, nil
-}
-
-// DelProfileLogByID method delete the profile history by ID
-func DelProfileLogByID(id int64) error {
- session := globalEngine.Table("profile_log")
- if _, err := session.Exec("delete from profile_log where id = ?", id); err != nil {
- return err
- }
- return nil
-}
-
-// GetProfileLogByID method get the profile history by id
-func GetProfileLogByID(query *GetProfileLog) error {
- query.Result = make([]*ProfileLog, 0)
- session := globalEngine.Table("profile_log")
- if err := session.Where("id = ?", query.ID).Find(&query.Result); err != nil {
- return err
- }
- return nil
-}
-
-// GetProfileMaxID method get the id profile history
-func GetProfileMaxID() (*ProfileLog, error) {
- profileLog := new(ProfileLog)
- session := globalEngine.Table("profile_log")
- has, err := session.Desc("id").Limit(1).Get(profileLog)
- if err != nil {
- return nil, err
- }
- if !has {
- return nil, nil
- }
- return profileLog, nil
-}
-
-// InActiveProfile method set the active field to false
-func InActiveProfile() error {
- session := globalEngine.Table("profile_log")
-
- if _, err := session.Exec("update class_profile set active=? where active = ?", false, true); err != nil {
- return err
- }
- return nil
-}
-
-func UpdateSchedule(typename string, strategy string) error {
- session := globalEngine.Table("schedule")
-
- item := new(Schedule)
- has, err := session.Where("type=?", typename).Get(item)
- if err != nil {
- log.Info("Schedule have not the type = ?", typename)
- return err
- } else if !has {
- _, err = session.Exec("insert into schedule (type, strategy) values (?, ?)", typename, strategy)
- if err != nil {
- log.Info("Insert Schedule values (?, ?)", typename, strategy)
- return err
- }
- } else {
- _, err = session.Exec("update schedule set type=?,strategy=? where type=?", typename, strategy, typename)
- log.Info(err)
- }
-
- return nil
-}
-
-func GetSchedule() []*Schedule {
- session := globalEngine.Table("schedule")
-
- items := make([]*Schedule, 0)
- if err := session.Find(&items); err != nil {
- return nil
- }
-
- return items
-}
diff --git a/common/sqlstore/sqlstore.go b/common/sqlstore/sqlstore.go
deleted file mode 100644
index a1b13a0..0000000
--- a/common/sqlstore/sqlstore.go
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package sqlstore
-
-import (
- "atune/common/config"
- "atune/common/log"
- "fmt"
- "os"
- "path"
-
- "github.com/go-xorm/xorm"
- _ "github.com/mattn/go-sqlite3" //import go-sqlite3 engine
-)
-
-var globalEngine *xorm.Engine
-
-// Sqlstore : struct for store db engine
-type Sqlstore struct {
- Cfg *config.Cfg
- engine *xorm.Engine
-}
-
-// Init method init the global db engine
-func (s *Sqlstore) Init() error {
-
- os.MkdirAll(config.DatabasePath, os.ModePerm)
- dbName := path.Join(config.DatabasePath, config.DatabaseName)
- connStr := "file:" + dbName + "?cache=shared&mode=rwc"
-
- log.Infof("Connecting to DB: %s", dbName)
-
- engine, err := xorm.NewEngine(config.DatabaseType, connStr)
- if err != nil {
- return fmt.Errorf("Faild to connect to database: %v", err)
- }
-
- s.engine = engine
- globalEngine = engine
-
- return nil
-}
-
-// Reload method, reload the db file for hot update
-func Reload(path string) error {
- if globalEngine != nil {
- globalEngine.Close()
- }
-
- connStr := "file:" + path + "?cache=shared&mode=rwc"
-
- log.Infof("Reload DB: %s", path)
- engine, err := xorm.NewEngine("sqlite3", connStr)
- if err != nil {
- return fmt.Errorf("Faild to connect to database: %v", err)
- }
-
- globalEngine = engine
- return nil
-}
diff --git a/common/system/system.go b/common/system/system.go
deleted file mode 100644
index 6f9c870..0000000
--- a/common/system/system.go
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package system
-
-type System struct {
- cpus []int
- irqs []int
- numa []int
- isolated []int
- nics []string
-}
-
-var instance *System = nil
-
-func (system *System) Init() error {
- return nil
-}
-
-func (system *System) GetAllCpu() []int {
- return system.cpus
-}
-
-func (system *System) GetCpu(numa int) []int {
- return system.cpus
-}
-
-func (system *System) GetIsolatedCpu() []int {
- return system.cpus
-}
-
-func (system *System) GetAllIrq() []int {
- return system.irqs
-}
-
-func (system *System) GetIrq(device string) []int {
- return system.irqs
-}
-
-func (system *System) GetNuma() []int {
- return system.numa
-}
-
-func (system *System) GetDeviceNuma(device string) int {
- return 0
-}
-
-func (system *System) GetNICs() []string {
- return system.nics
-}
-
-func (system *System) GetPids(Application string) []int {
- /* Get pid from application */
-
- return nil
-}
-
-func GetSystem() *System {
- if instance == nil {
- instance = new(System)
- instance.Init()
- }
-
- return instance
-}
diff --git a/common/tuning/hpre_tunning.go b/common/tuning/hpre_tunning.go
deleted file mode 100644
index bfdac26..0000000
--- a/common/tuning/hpre_tunning.go
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package tuning
-
-import (
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "strings"
-
- "github.com/caibirdme/yql"
- "github.com/mitchellh/mapstructure"
-)
-
-// Event : the content of response
-type Event struct {
- OverHead string `json:"overhead"`
- Object string `json:"object"`
- Symbol string `json:"symbol"`
-}
-
-// HprePostBody : body send to CPI service
-type HprePostBody struct {
- Section string `json:"section"`
- Key string `json:"key"`
-}
-
-// RespHprePost : response of CPI service
-type RespHprePost struct {
- Value string `json:"value"`
-}
-
-// Get method call the service of CPI
-func (h *HprePostBody) Get() (*RespHprePost, error) {
- url := config.GetUrl(config.ConfiguratorURI)
- res, err := http.Get(url, h)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
-
- if res.StatusCode != 200 {
- fmt.Println(res.StatusCode)
- respBody, err := ioutil.ReadAll(res.Body)
- fmt.Println(string(respBody), err)
- return nil, fmt.Errorf("get hpre support faild")
- }
-
- respBody, err := ioutil.ReadAll(res.Body)
- respPostIns := new(RespHprePost)
- err = json.Unmarshal(respBody, respPostIns)
- if err != nil {
- return nil, err
- }
- return respPostIns, nil
-}
-
-// HpreTuned method enable hpre if match the conditon
-func HpreTuned(m map[string]interface{}, expression string) (bool, error) {
- log.Infof("expression: %s", expression)
- for _, v := range m {
- switch vv := v.(type) {
- case []interface{}:
- for _, value := range vv {
- var event Event
- err := mapstructure.Decode(value, &event)
- if err != nil {
- log.Errorf("map %v convert to struct err %v", value, err)
- continue
- }
-
- log.Infof("OverHead: %f, Object: %s, Symbol: %s", event.OverHead, event.Object, event.Symbol)
-
- object := getObjectName(event.Object)
-
- match, err := yql.Match(expression, map[string]interface{}{
- "object": object,
- })
-
- if err != nil {
- log.Errorf("match error: %v", err)
- continue
- }
- if match {
- log.Infof("expression %s matches", expression)
- return true, nil
- }
- }
- }
-
- }
- return false, nil
-}
-
-func getObjectName(object string) string {
- objects := strings.Split(object, ".")
- if strings.Contains(objects[0], "-") {
- return strings.Split(objects[0], "-")[0]
- }
- return objects[0]
-}
-
-// IsSupportHpre method check system is support hpre or not, only can be used on ARM
-func IsSupportHpre() (bool, error) {
- body := &HprePostBody{
- Section: "bios",
- Key: "hpre_support",
- }
- respGetIns, err := body.Get()
- if err != nil {
- log.Infof("get support_hpre faild")
- return false, fmt.Errorf("get support_hpre faild")
- }
-
- if respGetIns.Value == "yes" {
- return true, nil
- }
-
- return false, nil
-}
diff --git a/common/tuning/optimizer.go b/common/tuning/optimizer.go
deleted file mode 100644
index 7412743..0000000
--- a/common/tuning/optimizer.go
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package tuning
-
-import (
- PB "atune/api/profile"
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "atune/common/project"
- "encoding/json"
- "fmt"
- "io/ioutil"
-)
-
-type optimizerBody struct {
- MaxEval int `json:"max_eval"`
- Knobs []knob `json:"knobs"`
-}
-
-type knob struct {
- Dtype string `json:"dtype"`
- Name string `json:"name"`
- Type string `json:"type"`
- Range []int64 `json:"range"`
- Items []int64 `json:"items"`
- Step int64 `json:"step"`
- Ref string `json:"ref"`
-}
-
-type respPostBody struct {
- TaskID string `json:task_id`
-}
-
-type optimizerPutBody struct {
- Iterations int `json:"iterations"`
- Value string `json:"value"`
-}
-
-type respPutBody struct {
- Param string `json:"param"`
-}
-
-func (o *optimizerBody) Post() (*respPostBody, error) {
- url := config.GetUrl(config.OptimizerURI)
- res, err := http.Post(url, o)
- if err != nil {
- return nil, err
- }
-
- defer res.Body.Close()
-
- respBody, err := ioutil.ReadAll(res.Body)
- respPostIns := new(respPostBody)
-
- err = json.Unmarshal(respBody, respPostIns)
- if err != nil {
- return nil, err
- }
-
- return respPostIns, nil
-}
-
-func (o *optimizerPutBody) Put(url string) (*respPutBody, error) {
- res, err := http.Put(url, o)
- if err != nil {
- return nil, err
- }
-
- defer res.Body.Close()
-
- respBody, err := ioutil.ReadAll(res.Body)
- respPutIns := new(respPutBody)
-
- err = json.Unmarshal(respBody, respPutIns)
- if err != nil {
- return nil, err
- }
-
- return respPutIns, nil
-
-}
-
-// Optimizer : the type implement the bayes serch service
-type Optimizer struct {
- Prj *project.YamlPrj
-}
-
-/*
-DynamicTuned method using bayes algorithm to search the best performance parameters
-*/
-func (o *Optimizer) DynamicTuned(ch chan *PB.AckCheck) error {
- //dynamic profle setting
- iterations := o.Prj.Iterations
- optimizerBody := new(optimizerBody)
- optimizerBody.MaxEval = iterations
-
- optimizerBody.Knobs = make([]knob, 0)
-
- for _, item := range o.Prj.Object {
- knob := new(knob)
- knob.Dtype = item.Info.Dtype
- knob.Name = item.Name
- knob.Type = item.Info.Type
- knob.Ref = item.Info.Ref
- knob.Range = item.Info.Scope
- knob.Items = item.Info.Items
- knob.Step = item.Info.Step
- optimizerBody.Knobs = append(optimizerBody.Knobs, *knob)
- }
-
- respPostIns, err := optimizerBody.Post()
- if err != nil {
- return err
- }
-
- log.Infof("create task id is %s", respPostIns.TaskID)
- url := config.GetUrl(config.OptimizerURI)
- optimizerPutURL := fmt.Sprintf("%s/%s", url, respPostIns.TaskID)
-
- log.Infof("optimizer put url is: %s", optimizerPutURL)
-
- var eval string
- for i := 0; i <= iterations+1; i++ {
- optPutBody := new(optimizerPutBody)
- optPutBody.Iterations = i
- optPutBody.Value = eval
-
- respPutIns, err := optPutBody.Put(optimizerPutURL)
- if err != nil {
- log.Errorf("get setting parameter error: %v", err)
- return err
- }
- if i == iterations {
- ch <- &PB.AckCheck{Name: fmt.Sprintf("Optimized result is: %s", respPutIns.Param)}
- break
- }
-
- log.Infof("setting params is: %s", respPutIns.Param)
- if err := o.Prj.RunSet(respPutIns.Param); err != nil {
- log.Error(err)
- return err
- }
-
- log.Info("set the parameter success")
- if err := o.Prj.RestartProject(); err != nil {
- log.Error(err)
- return err
- }
- log.Info("restart project success")
-
- benchmarkByte, err := o.Prj.BenchMark()
- if err != nil {
- log.Error(err)
- return err
- }
-
- eval, err = o.Prj.Evaluation(benchmarkByte)
- if err != nil {
- log.Error(err)
- return err
- }
-
- log.Info(eval)
- }
-
- resp, err := http.Delete(optimizerPutURL)
- if err != nil {
- log.Info("delete task faild:", err)
- }
- defer resp.Body.Close()
-
- resBytes, err := ioutil.ReadAll(resp.Body)
- log.Debug(string(resBytes))
- return nil
-}
diff --git a/common/tuning/rule_tunning.go b/common/tuning/rule_tunning.go
deleted file mode 100644
index 5b3f057..0000000
--- a/common/tuning/rule_tunning.go
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package tuning
-
-import (
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "atune/common/profile"
- "atune/common/sqlstore"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "strings"
-
- "github.com/caibirdme/yql"
-)
-
-// RuleBody : the body send to monitor service
-type RuleBody struct {
- Module string `json:"module"`
- Purpose string `json:"purpose"`
- Field string `json:"field"`
-}
-
-// Post method calling the monitor service
-func (r *RuleBody) Post() (*map[string]interface{}, error) {
- url := config.GetUrl(config.MonitorURI)
- res, err := http.Post(url, r)
- if err != nil {
- return nil, err
- }
-
- defer res.Body.Close()
- if res.StatusCode != 200 {
- log.Errorf("URL: %s, response code: %d", url, res.StatusCode)
- return nil, fmt.Errorf("get monitor data faild, url: %s", url)
- }
-
- respBody, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return nil, err
- }
- respPostIns := new(map[string]interface{})
-
- err = json.Unmarshal(respBody, respPostIns)
- if err != nil {
- return nil, err
- }
- return respPostIns, nil
-}
-
-/*
-RuleTuned method will be tuned the system parameter depend on the rules int the table
-if rule mached, it will perform the corresponding operation
-*/
-func RuleTuned(workloadType string) error {
- rules := &sqlstore.GetRuleTuned{Class: workloadType}
- if err := sqlstore.GetRuleTuneds(rules); err != nil {
- return err
- }
-
- if len(rules.Result) < 1 {
- log.Info("no rules to tuned")
- return nil
- }
-
- for _, rule := range rules.Result {
- rulePostBody := new(RuleBody)
-
- monitors := strings.Split(rule.Monitor, ".")
- if len(monitors) != 2 {
- log.Errorf("profile: %s, rule: %d, Monitor is not correct", workloadType, rule.ID)
- continue
- }
-
- rulePostBody.Module = monitors[0]
- rulePostBody.Purpose = monitors[1]
- rulePostBody.Field = rule.Field
-
- respPostIns, err := rulePostBody.Post()
- if err != nil {
- return err
- }
-
- if rule.Name == "hpre" {
- support, err := IsSupportHpre()
- if err != nil {
- continue
- }
- if !support {
- log.Info("current system is not support hpre")
- continue
- }
-
- match, _ := HpreTuned(*respPostIns, rule.Expression)
- if match {
- ruleAction(workloadType, rule.Action)
- } else {
- ruleAction(workloadType, rule.OppositeAction)
- }
-
- return nil
- }
- log.Info("response from server:", respPostIns)
- ruler, _ := yql.Rule(rule.Expression)
- match, err := ruler.Match(*respPostIns)
- if err != nil {
- log.Errorf("profile: %s, rule: %d, match error: %v", workloadType, rule.ID, err)
- continue
- }
-
- if match {
- ruleAction(workloadType, rule.Action)
- } else {
- ruleAction(workloadType, rule.OppositeAction)
- }
- }
- return nil
-}
-
-func ruleAction(workloadType string, action string) {
- pro, _ := profile.LoadFromWorkloadType(workloadType)
-
- pro.ActiveTuned(nil, action)
-}
diff --git a/common/utils/lock.go b/common/utils/lock.go
deleted file mode 100644
index f1d222c..0000000
--- a/common/utils/lock.go
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package utils
-
-import (
- "sync/atomic"
-)
-
-const (
- locked int32 = 1
-)
-
-// MutexLock : the type implement the TryLock function
-type MutexLock struct {
- state int32
-}
-
-// TryLock method if get the lock success, otherwise return false
-func (m *MutexLock) TryLock() bool {
- if !atomic.CompareAndSwapInt32(&m.state, 0, 1) {
- return false
- }
- return true
-}
-
-// Unlock method unlock lock flag
-func (m *MutexLock) Unlock() {
- atomic.CompareAndSwapInt32(&m.state, 1, 0)
-
-}
-
-// IsLocked method return wether the lock is already locked
-func (m *MutexLock) IsLocked() bool {
- if atomic.LoadInt32(&m.state) == locked {
- return true
- }
-
- return false
-
-}
diff --git a/common/utils/utils.go b/common/utils/utils.go
deleted file mode 100644
index ad4657f..0000000
--- a/common/utils/utils.go
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package utils
-
-import (
- PB "atune/api/profile"
- "bufio"
- "fmt"
- "io"
- "math/rand"
- "net"
- "os"
- "os/exec"
- "path"
- "path/filepath"
- "plugin"
- "strconv"
- "strings"
- "syscall"
- "time"
-
- "github.com/urfave/cli"
-)
-
-// disk filename
-const (
- diskFilename = "diskstats"
-)
-
-// the number of args
-const (
- ConstExactArgs = iota
- ConstMinArgs
-)
-
-// Status of AckCheck
-const (
- SUCCESS = "SUCCESS"
- FAILD = "FAILED"
- WARNING = "WARNING"
- REQUEST = "REQUEST"
- INFO = "INFO"
-)
-
-// CheckArgs method check command args num
-func CheckArgs(context *cli.Context, expected, checkType int) error {
- var err error
- cmdName := context.Command.Name
- switch checkType {
- case ConstExactArgs:
- if context.NArg() != expected {
- err = fmt.Errorf("%s: %q requires exactly %d argument(s)", os.Args[0], cmdName, expected)
- }
- case ConstMinArgs:
- if context.NArg() < expected {
- err = fmt.Errorf("%s: %q requires a minimum of %d argument(s)", os.Args[0], cmdName, expected)
- }
- }
-
- if err != nil {
- fmt.Printf("Incorrect Usage.\n\n")
- cli.ShowCommandHelp(context, cmdName)
- return err
- }
- return nil
-}
-
-// Fatal method exit the application
-func Fatal(err error) {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
-}
-
-// Random method return a random uint value, the source is the timestamp
-func Random() uint64 {
- rand.Seed(time.Now().Unix())
- return rand.Uint64()
-}
-
-// LoadPlugins method load the plugin service
-func LoadPlugins(path string) error {
- abs, err := filepath.Abs(path)
- if err != nil {
- return err
- }
-
- pattern := filepath.Join(abs, fmt.Sprintf("*"))
- libs, err := filepath.Glob(pattern)
- if err != nil {
- return err
- }
-
- for _, lib := range libs {
- if _, err := plugin.Open(lib); err != nil {
- fmt.Printf("load %s failed : err\n", lib, err)
- continue
- }
- }
-
- return nil
-}
-
-// PathExist method check path if exist or not
-func PathExist(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-// PathIsDir method check path is dir or not
-func PathIsDir(path string) (bool, error) {
- info, err := os.Stat(path)
- if err == nil {
- return info.IsDir(), nil
- }
- if os.IsNotExist(err) {
- return false, fmt.Errorf("path %s doens't exist", path)
- }
-
- return false, err
-}
-
-// Print method print AckCheck to stdout
-func Print(ackCheck *PB.AckCheck) {
- fc := 32
- if ackCheck.Status == FAILD {
- fc = 31
- } else if ackCheck.Status == WARNING {
- fc = 33
- } else if ackCheck.Status == REQUEST {
- fc = 36
- } else if ackCheck.Status == INFO {
- fc = 37
- }
- if ackCheck.Description == "" {
- fmt.Printf("%c[1;40;%dm %s %c[0m\n", 0x1B, fc, ackCheck.GetName(), 0x1B)
- } else {
- description := strings.Replace(ackCheck.Description, "\n", ",", -1)
- fmt.Printf(" [%c[1;40;%dm %-7s] %-40s %-50s %c[0m\n", 0x1B, fc, ackCheck.Status, ackCheck.Name, description, 0x1B)
- }
-}
-
-// PrintStr method print string to stdout
-func PrintStr(description string) {
-
- fmt.Printf("%c[1;40;%dm %s %c[0m\n", 0x1B, 32, description, 0x1B)
-}
-
-// IsHost method check whether it is a physical machine or a virtual machine
-func IsHost() bool {
- cmd := exec.Command("virt-what")
- _, err := cmd.Output()
- if err != nil {
- return false
- }
-
- return true
-}
-
-// CreateNamedPipe method create a named pip to communicatin
-func CreateNamedPipe() (string, error) {
- npipe := strconv.FormatInt(time.Now().Unix(), 10)
- npipe = path.Join("/tmp", npipe)
-
- exist, err := PathExist(npipe)
- if err != nil {
- return "", err
- }
- if exist {
- os.Remove(npipe)
- }
-
- err = syscall.Mkfifo(npipe, 0666)
- if err != nil {
- return "", err
- }
- return npipe, nil
-}
-
-// CopyFile method copy file from srcName to dstname
-func CopyFile(dstName string, srcName string) error {
- src, err := os.Open(srcName)
- if err != nil {
- return err
- }
- defer src.Close()
-
- dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
- if err != nil {
- return err
- }
- defer dst.Close()
-
- if _, err := io.Copy(dst, src); err != nil {
- return err
- }
- return nil
-
-}
-
-// RemoveDuplicateElement method remove duplicate elem from slice
-func RemoveDuplicateElement(message []string) []string {
- result := make([]string, 0, len(message))
- messageMap := map[string]struct{}{}
- for _, item := range message {
- if _, ok := messageMap[item]; !ok {
- messageMap[item] = struct{}{}
- result = append(result, item)
- }
- }
- return result
-}
-
-// WaitForPyservice method waiting for pyEngine service start success
-func WaitForPyservice() error {
- ticker := time.NewTicker(time.Second * 2)
- timeout := time.After(time.Second * 120)
- for {
- select {
- case <-ticker.C:
- _, err := net.Dial("tcp", "localhost:8383")
- if err != nil {
- continue
- }
- return nil
- case <-timeout:
- return fmt.Errorf("waiting for pyservice timeout")
- }
- }
- return nil
-}
-
-// InterfaceByName method check the interface state, up or down
-// if interface is not exist or down return err, otherwise return nil
-func InterfaceByName(name string) error {
- netIntface, err := net.InterfaceByName(name)
- if err != nil {
- return fmt.Errorf("interface %s is not exist", name)
- }
- if netIntface.Flags&net.FlagUp == 0 {
- return fmt.Errorf("interface %s may be down", name)
- }
- return nil
-}
-
-// DiskByName method check wether the disk is exist
-// if disk is exist return nil, otherwise return error
-func DiskByName(disk string) error {
- diskFile := path.Join("/proc", diskFilename)
- file, err := os.Open(diskFile)
- if err != nil {
- return fmt.Errorf("open file %s error: %v", diskFile, err)
- }
- defer file.Close()
-
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- parts := strings.Fields(scanner.Text())
- if len(parts) < 4 {
- continue
- }
- if parts[2] == disk {
- return nil
- }
- }
-
- return fmt.Errorf("disk %s is not exist", disk)
-}
diff --git a/database/init.sql b/database/init.sql
deleted file mode 100755
index 7cfa274..0000000
--- a/database/init.sql
+++ /dev/null
@@ -1,1191 +0,0 @@
-drop table if exists class_apps;
-CREATE TABLE IF NOT EXISTS class_apps(
- class TEXT PRIMARY KEY NOT NULL,
- apps TEXT,
- resource_limit TEXT,
- deletable BOOLEN NOT NULL
-);
-
-
-drop table if exists class_profile;
-CREATE TABLE IF NOT EXISTS class_profile(
- class TEXT PRIMARY KEY NOT NULL,
- profile_type TEXT NOT NULL,
- active BOOLEN NOT NULL
-);
-
-
-
-drop table if exists profile;
-CREATE TABLE IF NOT EXISTS profile(
- profile_type TEXT PRIMARY KEY NOT NULL,
- profile_information TEXT NOT NULL
-);
-
-
-drop table if exists tuned;
-CREATE TABLE IF NOT EXISTS tuned(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- class TEXT NOT NULL,
- name TEXT NOT NULL,
- type TEXT NOT NULL,
- value TEXT NOT NULL,
- range TEXT NOT NULL,
- step INTEGER,
- FOREIGN KEY(class) REFERENCES class_profile(class)
-);
-
-drop table if exists collection;
-CREATE TABLE IF NOT EXISTS collection(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- name TEXT NOT NULL,
- module TEXT NOT NULL,
- purpose TEXT NOT NULL,
- metrics TEXT NOT NULL
-);
-
-drop table if exists tuned_item;
-CREATE TABLE IF NOT EXISTS tuned_item(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- property TEXT NOT NULL,
- item TEXT NOT NULL
-);
-
-drop table if exists rule_tuned;
-CREATE TABLE IF NOT EXISTS rule_tuned(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- name TEXT NOT NULL,
- class TEXT NOT NULL,
- expression TEXT NOT NULL,
- action TEXT NOT NULL,
- opposite_action TEXT NOT NULL,
- monitor TEXT NOT NULL,
- field TEXT NOT NULL
-);
-
-drop table if exists profile_log;
-CREATE TABLE IF NOT EXISTS profile_log(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- profile_id TEXT NOT NULL,
- context TEXT NOT NULL,
- backup_path TEXT NOT NULL,
- timestamp DATETIME NOT NULL
-);
-
-drop table if exists schedule;
-CREATE TABLE IF NOT EXISTS schedule(
- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- type TEXT NOT NULL,
- strategy TEXT NOT NULL
-);
-
-
--- class_apps:
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("default", "", "", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("webserver", "nginx,httpd", "cpu, network", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("big_streaming_data", "", "network", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("big_database", "mongoDB,mysql,postgresql,mariadb", "cpu, memory, network, io", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("remote_storage", "ceph", "network, io", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("big_data_storage", "hadoop.micro.sort,hadoop.micro.terasort,hadoop.micro.wordcount,hadoop.micro.dfsioe.read,hadoop.micro.dfsioe.write,hadoop.sql.aggregation,hadoop.sql.join,hadoop.sql.scan,spark.micro.sort,spark.micro.wordcount,spark.sql.aggregation,spark.sql.join,spark.sql.scan", "io", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("big_data_computing", "hadoop.websearch.pagerank,hadoop.ml.bayes,hadoop.ml.kmeans,spark.micro.terasort,spark.websearch.pagerank,spark.ml.bayes,spark.ml.kmeans,spark.ml.als,spark.ml.rf,spark.ml.linear,spark.ml.svm,hadoop.ssd.sql.aggregation,hadoop.ssd.sql.join,hadoop.ssd.sql.scan", "cpu, io", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("in-memory_computing", "specjbb2015", "cpu, memory", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("in-memory_database", "redis", "cpu, network", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("high-performance_computing", "", "", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("single_computer_intensive_jobs", "speccpu2006", "cpu, memory", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("highly_interactive_task", "", "", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("communication", "dubbo", "cpu, network", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("real-time_task", "", "", 0);
-INSERT INTO class_apps(class, apps, resource_limit, deletable) VALUES("idle", "idle", "", 0);
-
--- class_profile:
-INSERT INTO class_profile(class, profile_type, active) VALUES("default", "default", 1);
-INSERT INTO class_profile(class, profile_type, active) VALUES("webserver", "ssl_webserver", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("big_streaming_data", "network-throughput", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("big_database", "database", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("big_data_computing", "big_data", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("big_data_storage", "big_data", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("remote_storage", "remote_storage", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("in-memory_computing", "in-memory_computing", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("in-memory_database", "in-memory_database", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("high-performance_computing", "hpc", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("highly_interactive_task", "network-latency", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("single_computer_intensive_jobs", "compute-intensive", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("communication", "rpc_communication", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("real-time_task", "real-time", 0);
-INSERT INTO class_profile(class, profile_type, active) VALUES("idle", "default", 0);
-
-
-
--- profile:
-INSERT INTO profile (profile_type, profile_information) VALUES("default", "
-#
-# atuned configuration for others, which could not be classified
-#
-[main]
-#TODO CONFIG
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-#TODO CONFIG
-
-[systemctl]
-#sysmonitor=stop
-#irqbalance=stop
-
-[tip]
-bind network interrupts to its affinity numa node = warning
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-check_environment=on
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("compute-intensive", "
-#
-# compute-intensive tuned configuration
-#
-[main]
-#TODO CONFIG
-
-[kernel_config]
-CONFIG_HZ=100
-CONFIG_ARM64_64K_PAGES=y
-
-[bios]
-Custom Refresh Rate=64ms
-Stream Write Mode=Allocate share LLC
-
-[bootloader.grub2]
-default_hugepagesz=2M
-hugepagesz=2M
-hugepages=230000
-
-[sysfs]
-kernel/mm/transparent_hugepage/defrag=never
-kernel/mm/transparent_hugepage/enabled=never
-
-[sysctl]
-kernel.randomize_va_space=0
-#vm.nr_hugepages=230000
-
-[tip]
-bind task to corresponding cpu core = error
-use optimized compile = warning
-
-[script]
-prefetch = off
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("io-intensive", "
-#
-# io-intensive tuned configuration
-#
-[main]
-#TODO CONFIG
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-# how to find the correct disk
-block/{disk}/queue/read_ahead_kb=4096
-
-[sysctl]
-vm.dirty_ratio=40
-vm.dirty_background_ratio=20
-vm.dirty_writeback_centisecs=800
-vm.dirty_expire_centisecs=30000
-
-[script]
-#TODO CONFIG
-
-[tip]
-mount your filesystem using noatime and nobarrier option = warning
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("remote_storage", "
-#
-# storage-intensive tuned configuration
-#
-[main]
-include=io-intensive
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[tip]
-use xfs as filesystem and mount-option using noatime and nobarrier = warning
-bind network interrupts to its affinity numa node = error
-
-[bootloader.grub2]
-iommu.passthrough=1
-
-[sysfs]
-block/{disk}/queue/read_ahead_kb=8192
-block/{disk}/queue/scheduler=deadline
-block/{disk}/queue/nr_requests=512
-
-[systemctl]
-sysmonitor=stop
-irqbalance=stop
-
-[sysctl]
-vm.swappiness=0
-kernel.pid_max = 4194303
-fs.file-max=200195456
-
-# Controls IP packet forwarding
-net.ipv4.ip_forward = 0
-
-# Controls source route verification
-net.ipv4.conf.default.rp_filter = 1
-
-# Do not accept source routing
-net.ipv4.conf.default.accept_source_route = 0
-
-# Controls the System Request debugging functionality of the kernel
-kernel.sysrq = 0
-
-# Controls whether core dumps will append the PID to the core filename.
-# Useful for debugging multi-threaded applications.
-kernel.core_uses_pid = 1
-
-# disable TIME_WAIT.. wait ..
-#net.ipv4.tcp_tw_recycle = 1
-net.ipv4.tcp_tw_reuse = 1
-
-# Controls the use of TCP syncookies
-net.ipv4.tcp_syncookies = 0
-
-# double amount of allowed conntrack
-#net.netfilter.nf_conntrack_max = 2621440
-#net.netfilter.nf_conntrack_tcp_timeout_established = 1800
-
-# Disable netfilter on bridges.
-#net.bridge.bridge-nf-call-ip6tables = 0
-#net.bridge.bridge-nf-call-iptables = 0
-#net.bridge.bridge-nf-call-arptables = 0
-
-# Controls the maximum size of a message, in bytes
-kernel.msgmnb = 65536
-
-# Controls the default maxmimum size of a mesage queue
-kernel.msgmax = 65536
-
-# Controls the maximum shared segment size, in bytes
-kernel.shmmax = 68719476736
-
-# Controls the maximum number of shared memory segments, in pages
-kernel.shmall = 4294967296
-
-[script]
-ifconfig = {network} mtu 9000
-ethtool = -G {network} rx 4096 tx 4096
-#ethtool = -K {network} lro on
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("network-latency", "
-#
-# network-latency tuned configuration
-# Optimize for deterministic performance at the cost of increased power consumption, focused on low latency network performance
-#
-[main]
-include=latency-performance
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-skew_tick=1
-
-[sysfs]
-kernel/mm/transparent_hugepage/defrag=never
-kernel/mm/transparent_hugepage/enabled=never
-
-[sysctl]
-net.core.busy_read=50
-net.core.busy_poll=50
-net.ipv4.tcp_fastopen=3
-kernel.numa_balancing=0
-
-[tip]
-#TODO CONFIG
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("network-throughput", "
-#
-# network-throughput tuned configuration
-# Optimize for streaming network throughput, generally only necessary on older CPUs or 40G+ networks
-#
-[main]
-include=throughput-performance
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-# Increase kernel buffer size maximums. Currently this seems only necessary at 40Gb speeds.
-#
-# The buffer tuning values below do not account for any potential hugepage allocation.
-# Ensure that you do not oversubscribe system memory.
-net.ipv4.tcp_rmem=4096 87380 16777216
-net.ipv4.tcp_wmem=4096 16384 16777216
-net.ipv4.udp_mem=3145728 4194304 16777216
-
-[tip]
-#TODO CONFIG
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("rpc_communication", "
-#
-# rpc_communication tuned configuration
-# Optimize for dubbo
-#
-[main]
-include=throughput-performance
-
-[bios]
-Custom Refresh Rate=64ms
-Power Policy = Performance
-
-[kernel_config]
-CONFIG_HZ=100
-
-[bootloader.grub2]
-default_hugepagesz=2M
-hugepagesz=2M
-hugepages=230000
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-kernel.sched_latency_ns = 16000000
-kernel.sched_min_granularity_ns = 3000000
-kernel.sched_migration_cost_ns = 1000
-
-[systemctl]
-sysmonitor=stop
-irqbalance=stop
-
-[script]
-prefetch = off
-ethtool = -K {network} gro on
-ethtool = -K {network} gso on
-ethtool = -K {network} tso on
-ethtool = -X {network} equal 32 hkey 6d:5a:56:da:25:5b:0e:c2:41:67:25:3d:43:a3:8f:b0:d0:ca:2b:cb:ae:7b:30:b4:77:cb:2d:a3:80:30:f2:0c:6a:42:b7:3b:be:ac:01:fa hfunc toeplitz
-swapoff = -a
-
-[tip]
-relogin into the system to enable limits setting = error
-bind your master process to the numa node that has the network card = error
-bind network interrupts to its affinity numa node = error
-
-[ulimit]
-{user}.hard.stack = unlimited
-{user}.soft.stack = unlimited
-{user}.hard.nofile = 32768
-{user}.soft.nofile = 32768
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("latency-performance", "
-#
-# latency-performance tuned configuration
-# Optimize for deterministic performance at the cost of increased power consumption
-#
-[main]
-#TODO CONFIG
-
-#[cpu]
-#force_latency=1
-#governor=performance
-#energy_perf_bias=performance
-#min_perf_pct=100
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-kernel.sched_min_granularity_ns=10000000
-
-vm.dirty_ratio=10
-vm.dirty_background_ratio=3
-vm.swappiness=10
-
-kernel.sched_migration_cost_ns=5000000
-
-[tip]
-#TODO CONFIG
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("throughput-performance", "
-#
-# throughput-performance tuned configuration
-# Broadly applicable tuning that provides excellent performance across a variety of common server workloads
-#
-[main]
-#TODO CONFIG
-
-#[cpu]
-#governor=performance
-#energy_perf_bias=performance
-#min_perf_pct=100
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-block/{disk}/queue/read_ahead_kb=4096
-
-[sysctl]
-kernel.sched_min_granularity_ns = 10000000
-kernel.sched_wakeup_granularity_ns = 15000000
-
-vm.dirty_ratio = 40
-vm.dirty_background_ratio = 10
-vm.swappiness=10
-
-[tip]
-#TODO CONFIG
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("real-time", "
-#
-# real-time tuned configuration
-# Optimize for realtime workloads
-#
-[main]
-include = network-latency
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-kernel.hung_task_timeout_secs = 600
-kernel.nmi_watchdog = 0
-kernel.sched_rt_runtime_us = -1
-vm.stat_interval = 10
-kernel.timer_migration = 0
-
-[tip]
-using isolated cores to run your real-time task = warning
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("ssl_webserver", "
-#
-# webserver tuned configuration
-#
-[main]
-#TODO CONFIG
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-fs.file-max=6553600
-fs.suid_dumpable = 1
-fs.aio-max-nr = 1048576
-kernel.shmmax = 68719476736
-kernel.shmall = 4294967296
-kernel.shmmni = 4096
-kernel.sem = 250 32000 100 128
-net.ipv4.tcp_tw_reuse = 1
-net.ipv4.tcp_syncookies = 1
-net.ipv4.ip_local_port_range = 1024 65500
-net.ipv4.tcp_max_tw_buckets = 5000
-net.core.somaxconn = 65535
-net.core.netdev_max_backlog = 262144
-net.ipv4.tcp_max_orphans = 262144
-net.ipv4.tcp_max_syn_backlog = 262144
-net.ipv4.tcp_timestamps = 0
-net.ipv4.tcp_synack_retries = 1
-net.ipv4.tcp_syn_retries = 1
-net.ipv4.tcp_fin_timeout = 1
-net.ipv4.tcp_keepalive_time = 60
-net.ipv4.tcp_mem = 362619 483495 725238
-net.ipv4.tcp_rmem = 4096 87380 6291456
-net.ipv4.tcp_wmem = 4096 16384 4194304
-net.core.wmem_default = 8388608
-net.core.rmem_default = 8388608
-net.core.rmem_max = 16777216
-net.core.wmem_max = 16777216
-
-[systemctl]
-sysmonitor=stop
-irqbalance=stop
-
-[bootloader.grub2]
-selinux=0
-iommu.passthrough=1
-
-[tip]
-bind your master process to the CPU near the network = error
-bind your network interrupt to the CPU that has this network = error
-relogin into the system to enable limits setting = error
-
-[script]
-openssl_hpre = 0
-prefetch = off
-
-[ulimit]
-{user}.hard.nofile = 102400
-{user}.soft.nofile = 102400
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("database", "
-#
-# database tuned configuration
-#
-[main]
-#TODO CONFIG
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[tip]
-use xfs as filesystem and mount-option using noatime and nobarrier = warning
-bind network interrupts to its affinity numa node = error
-relogin into the system to enable limits setting = error
-
-[bootloader.grub2]
-iommu.passthrough=1
-
-[sysctl]
-vm.swappiness=1
-
-# schedule
-kernel.sched_cfs_bandwidth_slice_us=21000
-kernel.sched_migration_cost_ns=1381000
-kernel.sched_latency_ns=16110000
-kernel.sched_min_granularity_ns=8250000
-kernel.sched_nr_migrate=53
-kernel.sched_wakeup_granularity_ns=50410000
-
-# network core
-net.core.rmem_default=21299200
-net.core.rmem_max=21299200
-net.core.wmem_default=21299200
-net.core.wmem_max=21299200
-net.ipv4.tcp_rmem=40960 8738000 62914560
-net.ipv4.tcp_wmem=40960 8738000 62914560
-net.core.dev_weight=97
-
-# support more connections for mysql
-net.ipv4.tcp_max_syn_backlog=20480
-net.core.somaxconn=1280
-
-[sysfs]
-block/{disk}/queue/read_ahead_kb=32
-block/{disk}/queue/scheduler=deadline
-kernel/mm/transparent_hugepage/defrag=never
-kernel/mm/transparent_hugepage/enabled=never
-
-[systemctl]
-sysmonitor=stop
-irqbalance=stop
-
-[script]
-prefetch = off
-
-[ulimit]
-{user}.hard.nofile = 102400
-{user}.soft.nofile = 102400
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("big_data", "
-#
-# big data computing tuned configuration
-#
-[main]
-include=io-intensive
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-iommu.passthrough=1
-
-[sysfs]
-#TODO CONFIG
-
-[systemctl]
-firewalld=stop
-sysmonitor=stop
-irqbalance=stop
-
-[tip]
-bind network interrupts to its affinity numa node = error
-relogin into the system to enable limits setting = error
-
-[sysctl]
-fs.file-max=1000000
-fs.nr_open=2000000
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-{user}.hard.nofile = 2000000
-{user}.soft.nofile = 1800000
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("in-memory_computing", "
-#
-# in-memory computing tuned configuration
-#
-[main]
-include=throughput-performance
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-Custom Refresh Rate=64ms
-Power Policy = Performance
-
-[bootloader.grub2]
-default_hugepagesz=2M
-hugepagesz=2M
-hugepages=102400
-
-[sysfs]
-#TODO CONFIG
-
-[sysctl]
-#vm.nr_hugepages=102400
-
-[script]
-prefetch = off
-
-[tip]
-use numactl to bind your task = warning
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("in-memory_database", "
-#
-# in-memory database tuned configuration, refer to sap hana, redis and memcached
-#
-[main]
-include=throughput-performance
-
-#[cpu]
-#force_latency=70
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-iommu.passthrough=1
-
-[sysctl]
-vm.overcommit_memory=1
-net.core.netdev_budget =600
-net.core.rmem_max =16777216
-net.core.somaxconn =2048
-net.core.optmem_max =40960
-net.core.rmem_default =65535
-net.core.wmem_default =65535
-net.core.wmem_max =8388608
-net.ipv4.tcp_rmem =16384 349520 16777216
-net.ipv4.tcp_wmem =16384 349520 16777216
-net.ipv4.tcp_mem =8388608 8388608 8388608
-
-kernel.sem = 32000 1024000000 500 32000
-kernel.numa_balancing = 0
-
-[sysfs]
-kernel/mm/transparent_hugepage/defrag=never
-kernel/mm/transparent_hugepage/enabled=never
-
-[systemctl]
-sysmonitor=stop
-irqbalance=stop
-
-[tip]
-leverage numactl to make CPU to access its local memory = error
-bind network interrupts to its affinity numa node = error
-
-[script]
-prefetch = off
-ifconfig = {network} mtu 1500
-ethtool = -c {network} adaptive-rx on
-ethtool = -K {network} gro on
-ethtool = -K {network} gso on
-ethtool = -K {network} tso on
-#ethtool = -K {network} lro on
-
-[ulimit]
-{user}.hard.nofile = 102400
-{user}.soft.nofile = 102400
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
-INSERT INTO profile (profile_type, profile_information) VALUES("hpc", "
-#
-# hpc tuned configuration, Optimize for HPC compute workloads
-#
-[main]
-include=latency-performance
-
-[kernel_config]
-#TODO CONFIG
-
-[bios]
-#TODO CONFIG
-
-[bootloader.grub2]
-#TODO CONFIG
-
-[sysfs]
-block/{disk}/queue/read_ahead_kb=4096
-kernel/mm/transparent_hugepage/enabled=always
-
-[sysctl]
-#vm.hugepages_treat_as_movable=0
-vm.min_free_kbytes=135168
-vm.zone_reclaim_mode=1
-kernel.numa_balancing=0
-net.core.busy_read=50
-net.core.busy_poll=50
-net.ipv4.tcp_fastopen=3
-
-[tip]
-#TODO CONFIG
-
-[script]
-#TODO CONFIG
-
-[ulimit]
-#TODO CONFIG
-
-[affinity.task]
-#TODO CONFIG
-
-[affinity.irq]
-#TODO CONFIG
-
-[check]
-#TODO CONFIG
-
-");
-
--- Performance Point
-INSERT INTO tuned_item(property, item) VALUES("check_environment", "Check");
-
-INSERT INTO tuned_item(property, item) VALUES("CONFIG_HZ", "Kernel");
-INSERT INTO tuned_item(property, item) VALUES("CONFIG_ARM64_64K_PAGES", "Kernel");
-
-INSERT INTO tuned_item(property, item) VALUES("iommu.passthrough", "Bootloader");
-INSERT INTO tuned_item(property, item) VALUES("default_hugepagesz", "Bootloader");
-INSERT INTO tuned_item(property, item) VALUES("hugepagesz", "Bootloader");
-INSERT INTO tuned_item(property, item) VALUES("hugepages", "Bootloader");
-INSERT INTO tuned_item(property, item) VALUES("selinux", "Bootloader");
-INSERT INTO tuned_item(property, item) VALUES("skew_tick", "Bootloader");
-
-INSERT INTO tuned_item(property, item) VALUES("openssl_hpre", "Library");
-
-INSERT INTO tuned_item(property, item) VALUES("Custom Refresh Rate", "BIOS");
-INSERT INTO tuned_item(property, item) VALUES("Stream Write Mode", "BIOS");
-INSERT INTO tuned_item(property, item) VALUES("Support Smmu", "BIOS");
-INSERT INTO tuned_item(property, item) VALUES("Max Payload Size", "BIOS");
-INSERT INTO tuned_item(property, item) VALUES("Power Policy", "BIOS");
-
-INSERT INTO tuned_item(property, item) VALUES("vm.nr_hugepages", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.swappiness", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.dirty_ratio", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.max_map_count", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.panic_on_oom", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.dirty_background_ratio", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.dirty_writeback_centisecs", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.dirty_expire_centisecs", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.overcommit_memory", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.zone_reclaim_mode", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.min_free_kbytes", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.hugepages_treat_as_movable", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel/mm/transparent_hugepage/defrag", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel/mm/transparent_hugepage/enabled", "OS");
-INSERT INTO tuned_item(property, item) VALUES("block/{disk}/queue/scheduler", "OS");
-INSERT INTO tuned_item(property, item) VALUES("block/{disk}/queue/read_ahead_kb", "OS");
-INSERT INTO tuned_item(property, item) VALUES("block/{disk}/queue/nr_requests", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_max_syn_backlog", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.somaxconn", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_keepalive_time", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_keepalive_probes", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_keepalive_intvl", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_retries2", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.ip_forward", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.conf.default.rp_filter", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.conf.default.accept_source_route", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_tw_recycle", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_tw_reuse", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_syncookies", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_tcp_timeout_established", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.bridge.bridge-nf-call-ip6tables", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.bridge.bridge-nf-call-iptables", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.bridge.bridge-nf-call-arptables", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.ip_local_port_range", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_max_tw_buckets", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.netdev_max_backlog", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_max_orphans", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_timestamps", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_synack_retries", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_syn_retries", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_fin_timeout", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_mem", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_rmem", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_wmem", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.udp_mem", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.tcp_fastopen", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.wmem_default", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.rmem_default", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.rmem_max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.wmem_max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_tcp_timeout_close_wait", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_tcp_timeout_fin_wait", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_tcp_timeout_time_wait", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.ipv4.conf.default.forwarding", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_buckets", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.netfilter.nf_conntrack_count", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.dev_weight", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.optmem_max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.netdev_budget", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.busy_read", "OS");
-INSERT INTO tuned_item(property, item) VALUES("net.core.busy_poll", "OS");
-INSERT INTO tuned_item(property, item) VALUES("ethtool", "OS");
-INSERT INTO tuned_item(property, item) VALUES("ifconfig", "OS");
-INSERT INTO tuned_item(property, item) VALUES("fs.file-max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("fs.nr_open", "OS");
-INSERT INTO tuned_item(property, item) VALUES("fs.suid_dumpable", "OS");
-INSERT INTO tuned_item(property, item) VALUES("fs.aio-max-nr", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.threads-max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sem", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.msgmnb", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.msgmax", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.shmmax", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.shmall", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.shmmni", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.pid_max", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.numa_balancing", "OS");
-INSERT INTO tuned_item(property, item) VALUES("{user}.hard.nofile", "OS");
-INSERT INTO tuned_item(property, item) VALUES("{user}.soft.nofile", "OS");
-INSERT INTO tuned_item(property, item) VALUES("{user}.soft.stack", "OS");
-INSERT INTO tuned_item(property, item) VALUES("{user}.hard.stack", "OS");
-INSERT INTO tuned_item(property, item) VALUES("swapoff", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.randomize_va_space", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_cfs_bandwidth_slice_us", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_migration_cost_ns", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_latency_ns", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_nr_migrate", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_min_granularity_ns", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_wakeup_granularity_ns", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sysrq", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.kstack_depth_to_print", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.panic_on_oops", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.panic", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.hung_task_timeout_secs", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.hung_task_panic", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.oom_dump_tasks", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.softlockup_panic", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.core_uses_pid", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.nmi_watchdog", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.sched_rt_runtime_us", "OS");
-INSERT INTO tuned_item(property, item) VALUES("vm.stat_interval", "OS");
-INSERT INTO tuned_item(property, item) VALUES("kernel.timer_migration", "OS");
-
-INSERT INTO tuned_item(property, item) VALUES("prefetch", "Chip");
-
-INSERT INTO tuned_item(property, item) VALUES("sysmonitor", "Service");
-INSERT INTO tuned_item(property, item) VALUES("irqbalance", "Service");
-INSERT INTO tuned_item(property, item) VALUES("firewalld", "Service");
-
-INSERT INTO tuned_item(property, item) VALUES("compile_optimization", "Compiler");
-INSERT INTO tuned_item(property, item) VALUES("compile_security", "Compiler");
-
--- collection table
-INSERT INTO collection(name, module, purpose, metrics) VALUES("cpu", "CPU", "STAT", "--interval=5; --fields=usr --fields=nice --fields=sys --fields=iowait --fields=irq --fields=soft --fields=steal --fields=guest --threshold=30 --fields=cutil");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("storage", "STORAGE", "STAT", "--interval=5;--device={disk} --fields=rs --fields=ws --fields=rMBs --fields=wMBs --fields=rrqm --fields=wrqm --fields=rareq-sz --fields=wareq-sz --fields=r_await --fields=w_await --fields=util --fields=aqu-sz");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("network", "NET", "STAT", "--interval=5;--nic={network} --fields=rxkBs --fields=txkBs --fields=rxpcks --fields=txpcks --fields=ifutil");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("network-err", "NET", "ESTAT", "--interval=5;--nic={network} --fields=errs --fields=util");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("mem.util", "MEM", "UTIL", "--interval=5;--fields=memused");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("mem.band", "MEM", "BANDWIDTH", "--interval=2;--fields=Total --fields=Total_Util");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("perf", "PERF", "STAT", "--interval=5;--fields=IPC --fields=CACHE-MISS-RATIO --fields=MPKI --fields=ITLB-LOAD-MISS-RATIO --fields=DTLB-LOAD-MISS-RATIO --fields=SBPI --fields=SBPC --fields=MEMORY-BOUND --fields=STORE-BOUND");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("vmstat", "MEM", "VMSTAT", "--interval=5;--fields=procs.b --fields=memory.swpd --fields=memory.free --fields=memory.buff --fields=memory.cache --fields=io.bi --fields=io.bo --fields=system.in --fields=system.cs --fields=util.swap --fields=util.cpu --fields=procs.r");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("sys.task", "SYS", "TASKS", "--interval=5;--fields=procs --fields=cswchs");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("sys.ldavg", "SYS", "LDAVG", "--interval=5;--fields=runq-sz --fields=plist-sz --fields=ldavg-1 --fields=ldavg-5 --fields=ldavg-15 --fields=task-util");
-INSERT INTO collection(name, module, purpose, metrics) VALUES("file.util", "SYS", "FDUTIL", "--interval=5;--fields=fd-util");
-
--- dynamic_tuned table
--- INSERT INTO rule_tuned(name, class, expression, action, opposite_action, monitor, field) VALUES("prefetch", "single_computer_intensive_jobs", "usr>80", "prefetch=off", "prefetch=on","CPU.STAT", ";--fields=usr");
-INSERT INTO rule_tuned(name, class, expression, action, opposite_action, monitor, field) VALUES("hpre", "webserver", "object in ('libssl', 'libcrypto')", "openssl_hpre=1", "openssl_hpre=0","PERF.TOP", ";--fields=overhead --fields=object --fields=symbol --addr-merge=0x3f");
-
--- AI search table
-INSERT INTO tuned (class, name, type, value, range) VALUES("single_computer_intensive_jobs", "prefetech", "ENUM", "off", "on,off" );
--- INSERT INTO tuned (class, name, type, value, range, step) VALUES("single_computer_intensive_jobs", "vm.nr_hugepages", "INT", 230000, "220000,240000", 10000 );
-
--- Schedule table
-INSERT INTO schedule (type, strategy) VALUES("all", "auto");
diff --git a/go.mod b/go.mod
deleted file mode 100644
index 835cdc7..0000000
--- a/go.mod
+++ /dev/null
@@ -1,20 +0,0 @@
-module opt
-
-require (
- github.com/antlr/antlr4 v0.0.0-20190726171924-e4737db19f4f // indirect
- github.com/bndr/gotabulate v1.1.2
- github.com/caibirdme/yql v0.0.0-20190801103415-238f3c90b514
- github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f
- github.com/go-ini/ini v1.42.0
- github.com/go-xorm/xorm v0.7.4
- github.com/golang/protobuf v1.3.1
- github.com/mattn/go-sqlite3 v1.11.0
- github.com/mitchellh/mapstructure v1.1.2
- github.com/sirupsen/logrus v1.4.2
- github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect
- github.com/urfave/cli v1.20.0
- golang.org/x/net v0.0.0-20190628185345-da137c7871d7
- google.golang.org/grpc v1.22.0
- gopkg.in/ini.v1 v1.48.0 // indirect
- gopkg.in/yaml.v2 v2.2.2
-)
diff --git a/go.sum b/go.sum
deleted file mode 100644
index 09873ff..0000000
--- a/go.sum
+++ /dev/null
@@ -1,208 +0,0 @@
-cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU=
-cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
-github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
-github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
-github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
-github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
-github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
-github.com/antlr/antlr4 v0.0.0-20190726171924-e4737db19f4f h1:GhBxi/Go5GISuLutOqoZ3RaWUpwiruwzlDPXLF0G40g=
-github.com/antlr/antlr4 v0.0.0-20190726171924-e4737db19f4f/go.mod h1:T7PbCXFs94rrTttyxjbyT5+/1V8T2TYDejxUfHJjw1Y=
-github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
-github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
-github.com/bndr/gotabulate v1.1.2 h1:yC9izuZEphojb9r+KYL4W9IJKO/ceIO8HDwxMA24U4c=
-github.com/bndr/gotabulate v1.1.2/go.mod h1:0+8yUgaPTtLRTjf49E8oju7ojpU11YmXyvq1LbPAb3U=
-github.com/caibirdme/yql v0.0.0-20190801103415-238f3c90b514 h1:h6EneDEcroVtN2e9uVH2fjk0X6QVTX8POWSUsPrlKBE=
-github.com/caibirdme/yql v0.0.0-20190801103415-238f3c90b514/go.mod h1:HD96PsY1swF6YCFZrtapRNs+elhAcYoNytu98CBsvhA=
-github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
-github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
-github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
-github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c=
-github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/denisenkom/go-mssqldb v0.0.0-20190707035753-2be1aa521ff4 h1:YcpmyvADGYw5LqMnHqSkyIELsHCGF6PkrmM31V8rF7o=
-github.com/denisenkom/go-mssqldb v0.0.0-20190707035753-2be1aa521ff4/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM=
-github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
-github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
-github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
-github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
-github.com/go-ini/ini v1.42.0 h1:TWr1wGj35+UiWHlBA8er89seFXxzwFn11spilrrj+38=
-github.com/go-ini/ini v1.42.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
-github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
-github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
-github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
-github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
-github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
-github.com/go-xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:9wScpmSP5A3Bk8V3XHWUcJmYTh+ZnlHVyc+A4oZYS3Y=
-github.com/go-xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:56xuuqnHyryaerycW3BfssRdxQstACi0Epw/yC5E2xM=
-github.com/go-xorm/xorm v0.7.4 h1:g/NgC590SzqV5VKmdRDNe/K3Holw3YJUCXX28r+rFGw=
-github.com/go-xorm/xorm v0.7.4/go.mod h1:vpza5fydeRgt+stvo9qgMhSNohYqmNt0I1/D6hkCekA=
-github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
-github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
-github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
-github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
-github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
-github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
-github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
-github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
-github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
-github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
-github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
-github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
-github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
-github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
-github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
-github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
-github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
-github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
-github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
-github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
-github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 h1:vr3AYkKovP8uR8AvSGGUK1IDqRa5lAAvEkZG1LKaCRc=
-github.com/jackc/fake v0.0.0-20150926172116-812a484cc733/go.mod h1:WrMFNQdiFJ80sQsxDoMokWK1W5TQtxBFNpzWTD84ibQ=
-github.com/jackc/pgx v3.3.0+incompatible h1:Wa90/+qsITBAPkAZjiByeIGHFcj3Ztu+VzrrIpHjL90=
-github.com/jackc/pgx v3.3.0+incompatible/go.mod h1:0ZGrqGqkRlliWnWB4zKnWtjbSWbGkVEFm4TeybAXq+I=
-github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
-github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
-github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
-github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
-github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
-github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
-github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
-github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
-github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
-github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
-github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
-github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
-github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
-github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
-github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
-github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
-github.com/mattn/go-sqlite3 v1.11.0 h1:LDdKkqtYlom37fkvqs8rMPFKAMe8+SgjbwZ6ex1/A/Q=
-github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
-github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
-github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
-github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
-github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
-github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
-github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
-github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
-github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
-github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
-github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
-github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
-github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs=
-github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
-github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
-github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
-github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
-github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
-github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
-github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
-github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
-github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24 h1:pntxY8Ary0t43dCZ5dqY4YTJCObLY1kIXl0uzMv+7DE=
-github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
-github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
-github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
-github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
-github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
-github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
-github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 h1:WN9BUFbdyOsSH/XohnWpXOlq9NBD5sGAB2FciQMUEe8=
-github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
-github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
-github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw=
-github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
-github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs=
-github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0=
-go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
-golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI=
-golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
-golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
-golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
-golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
-golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
-golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
-golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
-golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
-golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
-golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
-golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
-golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To=
-golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
-golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
-golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
-golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
-golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
-golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
-google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk=
-google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
-google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
-google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
-google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
-google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
-google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
-google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107 h1:xtNn7qFlagY2mQNFHMSRPjT2RkOV4OXM7P5TVy9xATo=
-google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
-google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
-google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
-google.golang.org/grpc v1.22.0 h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw=
-google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
-gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
-gopkg.in/ini.v1 v1.48.0 h1:URjZc+8ugRY5mL5uUeQH/a63JcHwdX9xZaWvmNWD7z8=
-gopkg.in/ini.v1 v1.48.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
-gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
-gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
-gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-xorm.io/builder v0.3.5 h1:EilU39fvWDxjb1cDaELpYhsF+zziRBhew8xk4pngO+A=
-xorm.io/builder v0.3.5/go.mod h1:ZFbByS/KxZI1FKRjL05PyJ4YrK2bcxlUaAxdum5aTR8=
-xorm.io/core v0.6.3 h1:n1NhVZt1s2oLw1BZfX2ocIJsHyso259uPgg63BGr37M=
-xorm.io/core v0.6.3/go.mod h1:8kz/C6arVW/O9vk3PgCiMJO2hIAm1UcuOL3dSPyZ2qo=
diff --git a/misc/atune-adm b/misc/atune-adm
deleted file mode 100644
index d3ee972..0000000
--- a/misc/atune-adm
+++ /dev/null
@@ -1,4 +0,0 @@
-# atune-adm completion -*- shell-script -*-
-complete -W "upgrade profile analysis check info list rollback tuning collection define undefine update train help" atune-adm
-
-# ex: filetype=sh
diff --git a/misc/atune.logo b/misc/atune.logo
deleted file mode 100644
index 976b6e9..0000000
--- a/misc/atune.logo
+++ /dev/null
@@ -1,46 +0,0 @@
-
- ````....---::::////////////-.`
- `.-//////::::/++/--++.```````./++//-.`
- `.-://:.`` -//:.` .+/` .++-.:++/:.`
- `-://:-`` `:+:` .+/` `://:. `:+/-///:.``
- `.:///-.` `:+- .+/` :+- `/+. `.-://:-``
- `.-///:.``...` `/+- `:+- `:+` `/+---..`.-://:-``
- -//:.` -:.-/` `/+/-.---` `/+-` `//` .++::///.` `.-://:-.`
- ./+-` `:-://-` `.--:+-`:: -//. `:+. :+. `:+:--. ``-://:`
- `-://. ` `-//:.` .---` `:+:` :+- `+/` /-`-: -+:`
- .-///-` ./+/. .//. `:+: :+- `---` -+:`
- `:+:.` `..` `-//- -+/` `--+: .+/ ``` -+:`
- :+- ./.-/` ./+-` -+- :-`-: :+. -:-:- -+/`
- :+: .//--:` `/+:` `.-.``````../+- `---` `+/ -:.:/` .++/`
- -+:` ./+:.`` -+- :-`:///////:::- `+/-` ..:+- .+/-+/`
- -+: ./+:. .+/ .:-:.`` ``.-:.` -:`./` .+: -+/` .+/`
- .++-..`` `./+:` /+` `..` `.``.-:///:://:-` `:-:- `/+. `.:+/` .+/`
- .++::////::/+:` `:+/` ./.-/` :-.:+/:.`` `-/+/-` `.+/``-///:.` .+/`
- ++` ``.-+/` -+/. ./-:: -:-:. `-/+- ``.-:/+/. /+-` :+-
- -+- .+/` ++` .---` -+: ` ``.. /+..-////-.` `+/` `++`
- `+/` .+/` .+/ `/``:- :+:` ``.://++- .+//-.` .+: -+-
- :+. `+/` :+- .-:/+- `:+: `----:/+//-.`.+: ` :+. `/+`
- .+: /+. `/+` `:+//+- -: .+-.` .+/ `/+` .+:
- /+` `-//. `+/ `/+: `-::. `/+:::::::::-` .:-:- `....../+`
- ./+:. :: ./ -+- -+/-. .:/-. ..........-:+/-` -:.-:` :+//////:
- .:+/-` `---` `.-:++-` `/.`:- `-/+:.:/+:.` `-/+/.` `.` :+.
- .:+/-``.-:/+/:-.-/+/-` -:::` `-+/-` .-/+/-` `-/+:. :+.
- `-/++/:..` `-/+:.` .:+/. `.:+/:.` ` .:+/:. ./+`
- ` `:/+:. `./+/---:::.` `.:/+:-:. `.:+/-.-/+:.
- `.://::/+++//:::---/+/:.` `:-.:: `/++/-`
- `.-..``` `.:/+/-.` ..` `:+/-`
- `.:///-`` `-/+:.`
- `-://:-``...--::/+/-`
- `.-////:::--..`
- `
- ______ ________
- / \ / |
- /$$$$$$ | $$$$$$$$/__ __ _______ ______
- $$ |__$$ | ______ $$ | / | / |/ \ / \
- $$ $$ |/ |$$ | $$ | $$ |$$$$$$$ |/$$$$$$ |
- $$$$$$$$ |$$$$$$/ $$ | $$ | $$ |$$ | $$ |$$ $$ |
- $$ | $$ | $$ | $$ \__$$ |$$ | $$ |$$$$$$$$/
- $$ | $$ | $$ | $$ $$/ $$ | $$ |$$ |
- $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$$/
-
-
diff --git a/misc/atuned.cnf b/misc/atuned.cnf
deleted file mode 100755
index 783970b..0000000
--- a/misc/atuned.cnf
+++ /dev/null
@@ -1,45 +0,0 @@
-
-#################################### server ###############################
-# atuned config
-[server]
-# the address the grpc server to bind to, default is 127.0.0.1
-address = 127.0.0.1
-
-# the atuned grpc listening port, default is 60001
-# the port can be set between 0 to 65535 the not be used
-port = 60001
-
-# the rest service listening port, default is 8383
-# the port can be set between 0 to 65535 than not be used
-rest_port = 8383
-
-# when run analysis command, the numbers of collected data.
-# default is 20
-sample_num = 20
-
-#################################### log ###############################
-[log]
-# log path, must be a absolute path
-path = /var/log/atuned
-
-# Either "debug", "info", "warn", "error", "critical", default is "info"
-level = info
-
-#################################### monitor ###############################
-[monitor]
-# With the module and format of the MPI, the format is {module}_{format}
-# The module is Either "mem", "net", "cpu", "STORAGE"
-# The purpose is "topo"
-module = mem_topo, cpu_topo
-
-#################################### system ###############################
-# you can add arbitrary key-value here, just like key = value
-# you can use the key in the profile
-[system]
-# the disk to be analysis
-disk = sda
-
-# the network to be analysis
-network = enp189s0f0
-
-user = root
diff --git a/misc/atuned.service b/misc/atuned.service
deleted file mode 100644
index 7655386..0000000
--- a/misc/atuned.service
+++ /dev/null
@@ -1,12 +0,0 @@
-[Unit]
-Description=EulerOS Auto Tuning Daemon
-After=systemd-sysctl.service network.target
-Requires=polkit.service
-
-[Service]
-Type=notify
-PIDFile=/run/atuned/atuned.pid
-ExecStart=/usr/bin/atuned
-
-[Install]
-WantedBy=multi-user.target
diff --git a/misc/atuned.spec b/misc/atuned.spec
deleted file mode 100755
index 385658f..0000000
--- a/misc/atuned.spec
+++ /dev/null
@@ -1,102 +0,0 @@
-# All right reserved by Huawei Co,Ltd
-
-%define __global_requires_exclude_from /usr/libexec
-#%define debug_package %{nil}
-
-Summary: AI auto tunning system
-Name: atune
-Version: 0.0.1
-Release: 1
-Packager: Huawei-2012-Euler-atuned
-Group: Development/System
-License: GPL
-BuildRequires: rpm-build
-Requires: systemd
-Source: %{name}-%{version}.tar.gz
-
-%description
-atune is a service for atuned AI tunning system.
-
-%prep
-%setup -q
-
-%build
-cd ../
-mkdir -p gopath/src/
-rm -rf gopath/src/%{name}
-mv %{name}-%{version} gopath/src/%{name}
-cd gopath/src/%{name}
-make
-cd ../
-\cp -rf %{name} ../../%{name}-%{version}
-
-%install
-mkdir -p %{buildroot}/etc/atuned
-mkdir -p %{buildroot}/usr/lib/atuned/modules
-mkdir -p %{buildroot}/usr/share/atuned
-mkdir -p %{buildroot}/usr/libexec/atuned/scripts
-mkdir -p %{buildroot}/usr/libexec/atuned/analysis
-mkdir -p %{buildroot}/usr/libexec/atuned/collector
-mkdir -p %{buildroot}%{_bindir}/
-mkdir -p %{buildroot}%{_unitdir}/
-mkdir -p %{buildroot}/var/lib/atuned
-mkdir -p %{buildroot}/usr/share/bash-completion/completions
-
-install -m 640 pkg/daemon_profile_server.so %{buildroot}/usr/lib/atuned/modules
-install -m 750 pkg/atune-adm %{buildroot}%{_bindir}/
-install -m 750 pkg/atuned %{buildroot}%{_bindir}/
-install -m 640 misc/atuned.service %{buildroot}%{_unitdir}/
-install -m 640 misc/atuned.cnf %{buildroot}/etc/atuned/
-install -m 640 database/atuned.db %{buildroot}/var/lib/atuned/
-install -m 640 misc/atune-adm %{buildroot}/usr/share/bash-completion/completions/
-install -m 640 misc/atune.logo %{buildroot}/usr/share/atuned
-\cp -rf scripts/* %{buildroot}/usr/libexec/atuned/scripts/
-install -m 640 kmodules/prefetch_tunning_per_cpu/prefetch_tunning.ko %{buildroot}/usr/libexec/atuned/scripts/prefetch
-chmod -R 750 %{buildroot}/usr/libexec/atuned/scripts/
-\cp -rf analysis/* %{buildroot}/usr/libexec/atuned/analysis/
-chmod -R 750 %{buildroot}/usr/libexec/atuned/analysis/
-\cp -rf libexec/* %{buildroot}/usr/libexec/atuned/collector/
-chmod -R 750 %{buildroot}/usr/libexec/atuned/collector/
-
-%files
-%defattr(0640,root,root,-)
-%attr(0640,root,root) /usr/lib/atuned/modules/daemon_profile_server.so
-%attr(0640,root,root) %{_unitdir}/atuned.service
-%attr(0750,root,root) %{_bindir}/atune-adm
-%attr(0750,root,root) %{_bindir}/atuned
-%attr(0750,root,root) /usr/libexec/atuned/scripts/*
-%attr(0750,root,root) /usr/libexec/atuned/analysis/*
-%attr(0750,root,root) /usr/libexec/atuned/collector/*
-%attr(0640,root,root) /usr/share/bash-completion/completions/atune-adm
-%attr(0750,root,root) /var/lib/atuned/atuned.db
-%attr(0750,root,root) %dir /usr/lib/atuned
-%attr(0750,root,root) %dir /usr/lib/atuned/modules
-%attr(0750,root,root) %dir /usr/libexec/atuned
-%attr(0750,root,root) %dir /usr/libexec/atuned/scripts
-%attr(0750,root,root) %dir /usr/libexec/atuned/analysis
-%attr(0750,root,root) %dir /usr/libexec/atuned/collector
-%attr(0750,root,root) %dir /usr/share/atuned
-%attr(0640,root,root) /usr/share/atuned/atune.logo
-%attr(0750,root,root) %dir /etc/atuned
-%attr(0750,root,root) /etc/atuned/*
-
-%post
-%systemd_post atuned.service
-
-%preun
-%systemd_preun atuned.service
-
-%postun
-%systemd_postun_with_restart atuned.service
-
-%changelog
-* Mon Jul 01 2019 Qiangmin Lin 0.0.1
-- Init atuned arch and code struct
-* Mon Jul 01 2019 Jianhai Luan 0.0.1
-* Mon Jul 01 2019 Xiaoguang Li 0.0.1
-* Mon Jul 01 2019 Wei Li 0.0.1
-- Init atuned
-* Mon Jul 01 2019 Xiaotong Ji 0.0.1
-- Init aware for ML
-* Mon Jul 01 2019 MingCong Song 0.0.1
-- Init DataSet Model
diff --git a/modules/client/profile/profile.go b/modules/client/profile/profile.go
deleted file mode 100644
index f46ab81..0000000
--- a/modules/client/profile/profile.go
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "math/rand"
- "strings"
- "time"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileCommand = cli.Command{
- Name: "profile",
- Usage: "active the specified workload type and check the actived workload type",
- UsageText: "atune-adm profile [OPTIONS] [WORKLOAD_TYPE]",
- Flags: []cli.Flag{
- cli.BoolFlag{
- Name: "check,c",
- Usage: "check the actived workload type",
- Hidden: false,
- },
- },
- Description: func() string {
- desc := `
- 1. active the specified workload_type,for example,avtive the idle workload type.
- example: atune-adm profile idle
- 2. check the actived workload type.
- example: atune-adm profile --check`
- return desc
- }(),
- Action: profile,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile",
- Desc: "opt profile system",
- NewInst: newProfileCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile service : %s\n", err)
- return
- }
-}
-
-func newProfileCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return profileCommand, nil
-}
-
-func profileCmdCheck(ctx *cli.Context) error {
- if ctx.NArg() > 1 {
- cli.ShowCommandHelp(ctx, "profile")
- return fmt.Errorf("only one workloadload type can be set")
- }
-
- if ctx.NArg() < 1 && !ctx.Bool("check") {
- cli.ShowCommandHelp(ctx, "profile")
- return fmt.Errorf("profile command can be active one workload type, or with --check")
- }
-
- if ctx.NArg() == 1 && ctx.Bool("check") {
- cli.ShowCommandHelp(ctx, "profile")
- return fmt.Errorf("profile args and --check can not be set at the same time")
- }
-
- return nil
-}
-
-func profile(ctx *cli.Context) error {
- if err := profileCmdCheck(ctx); err != nil {
- return err
- }
-
- if ctx.Bool("check") {
- return profileActiveCheck(ctx)
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Profile(CTX.Background(), &PB.ProfileInfo{Name: strings.Join(ctx.Args(), " ")})
- if err != nil {
- fmt.Println(err)
- return err
- }
- for {
- reply, err := stream.Recv()
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
-
- utils.Print(reply)
- num := rand.Intn(3)
- time.Sleep(time.Duration(num+1) * time.Second)
- }
-
- return nil
-}
-
-func profileActiveCheck(ctx *cli.Context) error {
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
-
- stream, err := svc.CheckActiveProfile(CTX.Background(), &PB.ProfileInfo{})
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- num := rand.Intn(3)
- time.Sleep(time.Duration(num+1) * time.Second)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_analysis.go b/modules/client/profile/profile_analysis.go
deleted file mode 100644
index 8ac8882..0000000
--- a/modules/client/profile/profile_analysis.go
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "path/filepath"
- "strings"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileAnalysisCommand = cli.Command{
- Name: "analysis",
- Usage: "analysis system workload type",
- ArgsUsage: "[APP_NAME]",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "model, m",
- Usage: "specified the the self traind model to analysis",
- Value: "",
- },
- },
- Description: func() string {
- desc := `
- analysis the system's workload type and optimization performance.
- you can specified the app name, but it's just for reference only.
- example: atune-adm analysis mysql
- you can also specify the self traind model to analysis, which only
- can be end with .m.
- example: atune-adm analysis --model ./self_traind.m`
- return desc
- }(),
- Action: profileAnalysis,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.analysis",
- Desc: "opt profile system",
- NewInst: newProfileAnalysisCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile analysis service : %s\n", err)
- return
- }
-}
-
-func newProfileAnalysisCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileAnalysisCommand, nil
-}
-
-func checkAnalysis(ctx *cli.Context) error {
- modelFlag := ctx.String("model")
- if modelFlag == "" {
- return nil
- }
- exist, err := utils.PathExist(modelFlag)
- if err != nil {
- return err
- }
- if !exist {
- return fmt.Errorf("model is not exist")
- }
-
- if !strings.HasSuffix(modelFlag, ".m") {
- return fmt.Errorf("model must be ends with .m")
- }
- return nil
-}
-
-func profileAnalysis(ctx *cli.Context) error {
- appname := ""
- if ctx.NArg() > 2 {
- return fmt.Errorf("only one or zero argument required")
- }
- if ctx.NArg() == 1 {
- appname = ctx.Args().Get(0)
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- modelFile := ctx.String("model")
- if modelFile != "" {
- modelFile, err = filepath.Abs(modelFile)
- if err != nil {
- return err
- }
- }
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Analysis(CTX.Background(), &PB.AnalysisMessage{Name: appname, Model: modelFile})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_charaterization.go b/modules/client/profile/profile_charaterization.go
deleted file mode 100644
index dae8ce1..0000000
--- a/modules/client/profile/profile_charaterization.go
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileCharaterCommand = cli.Command{
- Name: "charaterization",
- Usage: "analysis the workload type",
- ArgsUsage: "",
- Description: func() string {
- desc := "\n COMMAND:\n"
- return desc
- }(),
- Action: profileCharater,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.charaterization",
- Desc: "opt profile system",
- NewInst: newProfileCharaterCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile charaterization service : %s\n", err)
- return
- }
-}
-
-func newProfileCharaterCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileCharaterCommand, nil
-}
-
-func profileCharater(ctx *cli.Context) error {
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Charaterization(CTX.Background(), &PB.ProfileInfo{})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_check.go b/modules/client/profile/profile_check.go
deleted file mode 100644
index 9e26892..0000000
--- a/modules/client/profile/profile_check.go
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileCheckCommand = cli.Command{
- Name: "check",
- Usage: "check system basic information",
- ArgsUsage: "[arguments...]",
- Description: func() string {
- desc := "\n check system basic information\n"
- return desc
- }(),
- Action: profileCheck,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.check",
- Desc: "opt profile system",
- NewInst: newProfileCheckCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile check service : %s\n", err)
- return
- }
-}
-
-func newProfileCheckCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileCheckCommand, nil
-}
-
-func profileCheck(ctx *cli.Context) error {
- appname := ""
- if ctx.NArg() > 2 {
- return fmt.Errorf("only one or zero argument required")
- }
- if ctx.NArg() == 1 {
- appname = ctx.Args().Get(0)
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.CheckInitProfile(CTX.Background(), &PB.ProfileInfo{Name: appname})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_collection.go b/modules/client/profile/profile_collection.go
deleted file mode 100644
index d678fa2..0000000
--- a/modules/client/profile/profile_collection.go
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "path/filepath"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var collectionCommand = cli.Command{
- Name: "collection",
- Usage: "collect the system data for training",
- UsageText: "atune-adm collection OPTIONS",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "filename,f",
- Usage: "filename of the generated data file",
- Value: "",
- },
- cli.IntFlag{
- Name: "interval,i",
- Usage: "time interval for collecting data",
- Value: 5,
- },
- cli.IntFlag{
- Name: "duration,d",
- Usage: "the duration for collecting data",
- Value: 1200,
- },
- cli.StringFlag{
- Name: "output_path,o",
- Usage: "the output path of the collecting data",
- Value: "",
- },
- cli.StringFlag{
- Name: "disk,b",
- Usage: "the disk to be collected",
- Value: "",
- },
- cli.StringFlag{
- Name: "network,n",
- Usage: "the network to be collected",
- Value: "",
- },
- cli.StringFlag{
- Name: "workload_type,t",
- Usage: "the workload type of the collected data",
- Value: "",
- },
- },
- Description: func() string {
- desc := `
- collect data for train machine learning model, you must set the command options
- which has no default value, the output_path must be a absolute path.
- example: atune-adm collection -f mysql -i 5 -d 1200 -o /home -b sda -n eth0 -t idle`
- return desc
- }(),
- Action: collection,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.collection",
- Desc: "opt profile system",
- NewInst: newCollectionCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load collection service : %s\n", err)
- return
- }
-}
-
-func newCollectionCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return collectionCommand, nil
-}
-
-func checkCollectionCtx(ctx *cli.Context) error {
- if ctx.String("filename") == "" {
- cli.ShowCommandHelp(ctx, "collection")
- return fmt.Errorf("error: filename must be specified")
- }
-
- if len(ctx.String("filename")) > 255 {
- return fmt.Errorf("error: filename length is longer than 255 charaters")
- }
-
- if ctx.String("disk") == "" {
- cli.ShowCommandHelp(ctx, "collection")
- return fmt.Errorf("error: disk block must be specified")
- }
- if ctx.String("network") == "" {
- cli.ShowCommandHelp(ctx, "collection")
- return fmt.Errorf("error: network must be specified")
- }
-
- if ctx.String("workload_type") == "" {
- cli.ShowCommandHelp(ctx, "collection")
- return fmt.Errorf("error: workload type must be specified")
- }
-
- if ctx.String("output_path") == "" {
- cli.ShowCommandHelp(ctx, "collection")
- return fmt.Errorf("error: output_path must be specified")
- }
-
- if ctx.Int64("interval") < 1 || ctx.Int64("interval") > 60 {
- return fmt.Errorf("error: collection interval value must be between 1 and 60 seconds")
- }
-
- if ctx.Int64("duration") < ctx.Int64("interval")*10 {
- return fmt.Errorf("error: collection duration value must be bigger than interval*10")
- }
-
- if !filepath.IsAbs(ctx.String("output_path")) {
- return fmt.Errorf("error: output path must be absolute path")
- }
-
- return nil
-}
-
-func collection(ctx *cli.Context) error {
- if err := checkCollectionCtx(ctx); err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- outputPath := ctx.String("output_path")
- outputPath, err = filepath.Abs(outputPath)
- if err != nil {
- return err
- }
- message := PB.CollectFlag{
- Interval: ctx.Int64("interval"),
- Duration: ctx.Int64("duration"),
- Workload: ctx.String("filename"),
- OutputPath: outputPath,
- Block: ctx.String("disk"),
- Network: ctx.String("network"),
- Type: ctx.String("workload_type"),
- }
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Collection(CTX.Background(), &message)
- if err != nil {
- fmt.Println(err)
- return err
- }
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_define.go b/modules/client/profile/profile_define.go
deleted file mode 100644
index da1d61a..0000000
--- a/modules/client/profile/profile_define.go
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io/ioutil"
-
- "github.com/go-ini/ini"
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileDefineCommand = cli.Command{
- Name: "define",
- Usage: "create a new workload type",
- ArgsUsage: "WORKLOAD_TYPE PROFILE_NAME PROFILE_FILE",
- Description: func() string {
- desc := `
- create a new workload type which can not be already exist, for example
- below, create a new WORKLOAD_TYPE with name test_type, PROFILE_NAME with
- test_name, PROFILE_FILE with ./example.conf.
- example: atune-adm define test_type test_name ./example.conf
- `
- return desc
- }(),
- Action: profileDefined,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.define",
- Desc: "opt profile system",
- NewInst: newProfileDefine,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile service : %s\n", err)
- return
- }
-}
-
-func newProfileDefine(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return profileDefineCommand, nil
-}
-
-func profileDefineCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 3, utils.ConstExactArgs); err != nil {
- return err
- }
-
- file := ctx.Args().Get(2)
- exist, err := utils.PathExist(file)
- if err != nil {
- return err
- }
- if !exist {
- return fmt.Errorf("file %s is not exist", file)
- }
-
- _, err = ini.Load(file)
- if err != nil {
- return fmt.Errorf("load profile faild, file format may be not correct")
- }
-
- return nil
-}
-
-func profileDefined(ctx *cli.Context) error {
- if err := profileDefineCheck(ctx); err != nil {
- return err
- }
- workloadType := ctx.Args().Get(0)
- profileName := ctx.Args().Get(1)
-
- data, err := ioutil.ReadFile(ctx.Args().Get(2))
- if err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- reply, err := svc.Define(CTX.Background(), &PB.DefineMessage{WorkloadType: workloadType, ProfileName: profileName, Content: data})
- if err != nil {
- fmt.Println(err)
- return err
- }
- if reply.GetStatus() != "OK" {
- fmt.Println(reply.GetStatus())
- return nil
- }
- fmt.Println("define a new workload type success")
- return nil
-}
diff --git a/modules/client/profile/profile_info.go b/modules/client/profile/profile_info.go
deleted file mode 100644
index c96f721..0000000
--- a/modules/client/profile/profile_info.go
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "strings"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileInfoCommand = cli.Command{
- Name: "info",
- Usage: "display profile info corresponding to specified workload type",
- ArgsUsage: "WORKLOAD_TYPE",
- Description: func() string {
- desc := "\n display profile info corresponding to WORKLOAD_TYPE\n"
- return desc
- }(),
- Action: profileInfo,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.info",
- Desc: "opt profile system",
- NewInst: newProfileInfoCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile list service : %s\n", err)
- return
- }
-}
-
-func newProfileInfoCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileInfoCommand, nil
-}
-
-func profileInfoCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 1, utils.ConstExactArgs); err != nil {
- return err
- }
-
- return nil
-}
-
-func profileInfo(ctx *cli.Context) error {
- if err := profileInfoCheck(ctx); err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
-
- stream, err := svc.InfoProfile(CTX.Background(), &PB.ProfileInfo{Name: strings.Join(ctx.Args(), " ")})
- if err != nil {
- return err
- }
-
- for {
- reply, err := stream.Recv()
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
-
- fmt.Print(reply.Name)
-
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_list.go b/modules/client/profile/profile_list.go
deleted file mode 100644
index 2b65aed..0000000
--- a/modules/client/profile/profile_list.go
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
-
- "github.com/bndr/gotabulate"
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileListCommand = cli.Command{
- Name: "list",
- Usage: "list support workload type",
- UsageText: "atune-adm list",
- Description: func() string {
- desc := "\n list current support workload type\n"
- return desc
- }(),
- Action: profileList,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.list",
- Desc: "opt profile system",
- NewInst: newProfileListCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile list service : %s\n", err)
- return
- }
-}
-
-func newProfileListCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileListCommand, nil
-}
-
-func profileListCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 0, utils.ConstExactArgs); err != nil {
- return err
- }
-
- return nil
-}
-
-func profileList(ctx *cli.Context) error {
- if err := profileListCheck(ctx); err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.ListWorkload(CTX.Background(), &PB.ProfileInfo{})
- if err != nil {
- return err
- }
-
- table := make([][]string, 0)
- fmt.Println("\nSupport WorkloadTypes:")
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- row := make([]string, 0)
- row = append(row, reply.WorkloadType)
- row = append(row, reply.ProfileNames)
- row = append(row, reply.Active)
-
- table = append(table, row)
- }
-
- tabulate := gotabulate.Create(table)
- tabulate.SetHeaders([]string{"WorkloadType", "ProfileName", "Active"})
- tabulate.SetAlign("left")
- tabulate.SetMaxCellSize(60)
- tabulate.SetWrapStrings(true)
- fmt.Println(tabulate.Render("grid"))
-
- return nil
-}
diff --git a/modules/client/profile/profile_rollback.go b/modules/client/profile/profile_rollback.go
deleted file mode 100644
index edfa32a..0000000
--- a/modules/client/profile/profile_rollback.go
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileRollbackCommand = cli.Command{
- Name: "rollback",
- Usage: "rollback to the system init state",
- UsageText: "atune-adm rollback",
- Description: func() string {
- desc := `rollback the system config to the init state`
- return desc
- }(),
- Action: profileRollback,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.rollback",
- Desc: "opt profile system",
- NewInst: newProfileRollbackCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile rollback service : %s\n", err)
- return
- }
-}
-
-func newProfileRollbackCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileRollbackCommand, nil
-}
-
-func profileRollbackCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 0, utils.ConstExactArgs); err != nil {
- return err
- }
-
- return nil
-}
-
-func profileRollback(ctx *cli.Context) error {
- if err := profileRollbackCheck(ctx); err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.ProfileRollback(CTX.Background(), &PB.ProfileInfo{})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_schedule.go b/modules/client/profile/profile_schedule.go
deleted file mode 100644
index 7dc25b2..0000000
--- a/modules/client/profile/profile_schedule.go
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "strings"
- "fmt"
- "io"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var scheduleCommand = cli.Command{
- Name: "schedule",
- Usage: "schedule",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "type,t",
- Usage: "--type=[cpu|irq|all]",
- Value: "all",
- },
- cli.StringFlag{
- Name: "strategy,s",
- Usage: "--strategy=[performance|powersave|auto]",
- Value: "auto",
- },
- },
- ArgsUsage: "[arguments...]",
- Description: func() string {
- desc := "\n schedule: schedule all available resource into system \n"
- return desc
- }(),
- Action: schedule,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.schedule",
- Desc: "opt profile system",
- NewInst: newScheduleCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load schedule service : %s\n", err)
- return
- }
-}
-
-func newScheduleCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return scheduleCommand, nil
-}
-
-func checkScheduleCtx(ctx *cli.Context) error {
- typename := ctx.String("type")
- if !((typename == "cpu") || (typename == "irq") || (typename == "all")) {
- return fmt.Errorf("type have error exist")
- }
-
- strategy := ctx.String("strategy")
- if !((strategy == "performance") || (strategy == "powersave") || (strategy == "auto")) {
- return fmt.Errorf("strategy have error exist")
- }
-
- return nil
-}
-
-func schedule(ctx *cli.Context) error {
- if err := checkScheduleCtx(ctx); err != nil {
- return err
- }
-
- appname := strings.Join(ctx.Args(), ",")
- typename := ctx.String("type")
- strategy := ctx.String("strategy")
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Schedule(CTX.Background(), &PB.ScheduleMessage{App: appname, Type: typename, Strategy: strategy})
- for {
- _, err := stream.Recv()
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_train.go b/modules/client/profile/profile_train.go
deleted file mode 100644
index 26b06a1..0000000
--- a/modules/client/profile/profile_train.go
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "os"
- "path/filepath"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var trainCommand = cli.Command{
- Name: "train",
- Usage: "train a new model with self collected data",
- UsageText: "atune-adm train OPTIONS",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "data_path,d",
- Usage: "the path where has data for training",
- Value: "",
- },
- cli.StringFlag{
- Name: "output_file,o",
- Usage: "the model to be generated",
- Value: "",
- },
- },
- Description: func() string {
- desc := `
- training a new model with the self collected data, data_path option specified
- the path that storage the collected data, the collected data must have more
- than two workload type. output_file specified the file path where to store
- the trained model, which must be end with .m.
- example: atune-adm train --data_path=./data --output_file=./model/trained.m`
- return desc
- }(),
- Action: train,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.train",
- Desc: "opt profile system",
- NewInst: newTrainCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load collection service : %s\n", err)
- return
- }
-}
-
-func newTrainCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return trainCommand, nil
-}
-
-func checkTrainCtx(ctx *cli.Context) error {
- dataPath := ctx.String("data_path")
- if dataPath == "" {
- cli.ShowCommandHelp(ctx, "train")
- return fmt.Errorf("error: data_path must be specified")
- }
-
- outputPath := ctx.String("output_file")
- if outputPath == "" {
- cli.ShowCommandHelp(ctx, "train")
- return fmt.Errorf("error: output_file must be specified")
- }
-
- return nil
-}
-
-func train(ctx *cli.Context) error {
- if err := checkTrainCtx(ctx); err != nil {
- return err
- }
-
- dataPath, err := filepath.Abs(ctx.String("data_path"))
- if err != nil {
- return err
- }
- outputPath, err := filepath.Abs(ctx.String("output_file"))
- if err != nil {
- return err
- }
-
- dir := filepath.Dir(outputPath)
-
- exist, err := utils.PathExist(dir)
- if err != nil {
- return err
- }
- if !exist {
- os.MkdirAll(dir, 0660)
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Training(CTX.Background(), &PB.TrainMessage{DataPath: dataPath, OutputPath: outputPath})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
- fmt.Println("the model generate path:", outputPath)
- return nil
-}
diff --git a/modules/client/profile/profile_tuning.go b/modules/client/profile/profile_tuning.go
deleted file mode 100644
index e6c4b3a..0000000
--- a/modules/client/profile/profile_tuning.go
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "io/ioutil"
- "strings"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
- yaml "gopkg.in/yaml.v2"
-)
-
-var profileTunningCommand = cli.Command{
- Name: "tuning",
- Usage: "dynamic bayes search optimal parameter sets",
- ArgsUsage: "PROJECT_YAML",
- Description: func() string {
- desc := `
- tuning command usning bayes method dynamic search optimal parameter sets,
- the PROJECT_YAML which you can refer to Documentation example.yaml.
- example: atune-adm tuning ./example.yaml
- `
- return desc
- }(),
- Action: profileTunning,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.tunning",
- Desc: "opt profile system",
- NewInst: newProfileTuningCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile analysis service : %s\n", err)
- return
- }
-}
-
-func newProfileTuningCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileTunningCommand, nil
-}
-
-func profileTunning(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 1, utils.ConstExactArgs); err != nil {
- return err
- }
-
- yamlPath := ctx.Args().Get(0)
- exist, err := utils.PathExist(yamlPath)
- if err != nil {
- return err
- }
-
- if !exist {
- return fmt.Errorf("project file %s is not exist", yamlPath)
- }
-
- if !strings.HasSuffix(yamlPath, ".yaml") && !strings.HasSuffix(yamlPath, ".yml") {
- return fmt.Errorf("project file is not ends with yaml or yml")
- }
-
- data, err := ioutil.ReadFile(yamlPath)
- if err != nil {
- return err
- }
- var yamlStruct interface{}
- if err := yaml.Unmarshal(data, &yamlStruct); err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- stream, err := svc.Tuning(CTX.Background(), &PB.ProfileInfo{Name: string(data)})
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/client/profile/profile_undefine.go b/modules/client/profile/profile_undefine.go
deleted file mode 100644
index 02a3b10..0000000
--- a/modules/client/profile/profile_undefine.go
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileDeleteCommand = cli.Command{
- Name: "undefine",
- Usage: "delete the specified workload type",
- ArgsUsage: "WORKLOAD_TYPE",
- Description: func() string {
- desc := "\n delete the specified workload type, only self defined workload type can be delete.\n"
- return desc
- }(),
- Action: profileDelete,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.undefine",
- Desc: "opt profile system",
- NewInst: newProfileDelete,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile service : %s\n", err)
- return
- }
-}
-
-func newProfileDelete(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return profileDeleteCommand, nil
-}
-
-func profileDeleteCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 1, utils.ConstExactArgs); err != nil {
- return err
- }
-
- return nil
-}
-
-func profileDelete(ctx *cli.Context) error {
- if err := profileDeleteCheck(ctx); err != nil {
- return err
- }
- workloadType := ctx.Args().Get(0)
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- reply, err := svc.Delete(CTX.Background(), &PB.DefineMessage{WorkloadType: workloadType})
- if err != nil {
- fmt.Println(err)
- return err
- }
- if reply.GetStatus() != "OK" {
- fmt.Println(reply.GetStatus())
- return nil
- }
- fmt.Println("delete workload type success")
- return nil
-}
diff --git a/modules/client/profile/profile_update.go b/modules/client/profile/profile_update.go
deleted file mode 100644
index 097e821..0000000
--- a/modules/client/profile/profile_update.go
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io/ioutil"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileUpdateCommand = cli.Command{
- Name: "update",
- Usage: "update the optimization content of the specified workload type and profile name",
- ArgsUsage: "WORKLOAD_TYPE PROFILE_NAME PROFILE_FILE",
- Description: func() string {
- desc := `
- update the optimization content of the specified workload type and profile name,
- example: atune-adm update idle default ./update.conf
- `
- return desc
- }(),
- Action: profileUpdate,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile.update",
- Desc: "opt profile system",
- NewInst: newProfileUpdate,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile service : %s\n", err)
- return
- }
-}
-
-func newProfileUpdate(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- return profileUpdateCommand, nil
-}
-
-func profileUpdateCheck(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 3, utils.ConstExactArgs); err != nil {
- return err
- }
-
- file := ctx.Args().Get(2)
- exist, err := utils.PathExist(file)
- if err != nil {
- return err
- }
- if !exist {
- return fmt.Errorf("file %s is not exist", file)
- }
-
- return nil
-}
-
-func profileUpdate(ctx *cli.Context) error {
- if err := profileUpdateCheck(ctx); err != nil {
- return err
- }
- workloadType := ctx.Args().Get(0)
- profileName := ctx.Args().Get(1)
-
- data, err := ioutil.ReadFile(ctx.Args().Get(2))
- if err != nil {
- return err
- }
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
- reply, err := svc.Update(CTX.Background(), &PB.DefineMessage{WorkloadType: workloadType, ProfileName: profileName, Content: data})
- if err != nil {
- fmt.Println(err)
- return nil
- }
- if reply.GetStatus() != "OK" {
- fmt.Println(reply.GetStatus())
- return nil
- }
-
- fmt.Println("update workload type success")
- return nil
-}
diff --git a/modules/client/profile/profile_upgrade.go b/modules/client/profile/profile_upgrade.go
deleted file mode 100644
index 6a4a7c9..0000000
--- a/modules/client/profile/profile_upgrade.go
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package profile
-
-import (
- PB "atune/api/profile"
- "atune/common/client"
- SVC "atune/common/service"
- "atune/common/utils"
- "fmt"
- "io"
- "path/filepath"
- "strings"
-
- "github.com/urfave/cli"
- CTX "golang.org/x/net/context"
-)
-
-var profileUpgradeCommand = cli.Command{
- Name: "upgrade",
- Usage: "upgrade the database",
- ArgsUsage: "DB_PATH",
- Description: func() string {
- desc := "\n upgrade the database with the specified db file\n"
- return desc
- }(),
- Action: profileUpgrade,
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "atune.upgrade",
- Desc: "atune upgrade system",
- NewInst: newProfileUpgradeCmd,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load profile upgrade service : %s\n", err)
- return
- }
-}
-
-func newProfileUpgradeCmd(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
-
- return profileUpgradeCommand, nil
-}
-
-func profileUpgrade(ctx *cli.Context) error {
- if err := utils.CheckArgs(ctx, 1, utils.ConstExactArgs); err != nil {
- return err
- }
-
- dbPath := ctx.Args().Get(0)
- exist, err := utils.PathExist(dbPath)
- if err != nil {
- return err
- }
-
- if !exist {
- return fmt.Errorf("%s is not exist", dbPath)
- }
-
- if !strings.HasSuffix(dbPath, ".db") {
- return fmt.Errorf("database format is not correct")
- }
-
- absPath, _ := filepath.Abs(dbPath)
-
- c, err := client.NewClientFromContext(ctx)
- if err != nil {
- return err
- }
- defer c.Close()
-
- svc := PB.NewProfileMgrClient(c.Connection())
-
- stream, err := svc.UpgradeProfile(CTX.Background(), &PB.ProfileInfo{Name: absPath})
- if err != nil {
- return err
- }
-
- for {
- reply, err := stream.Recv()
-
- if err == io.EOF {
- break
- }
-
- if err != nil {
- return err
- }
-
- utils.Print(reply)
- }
-
- return nil
-}
diff --git a/modules/server/profile/profile.go b/modules/server/profile/profile.go
deleted file mode 100644
index ae53f45..0000000
--- a/modules/server/profile/profile.go
+++ /dev/null
@@ -1,1023 +0,0 @@
-/*
- * Copyright (c) 2019 Huawei Technologies Co., Ltd.
- * A-Tune is licensed under the Mulan PSL v1.
- * You can use this software according to the terms and conditions of the Mulan PSL v1.
- * You may obtain a copy of Mulan PSL v1 at:
- * http://license.coscl.org.cn/MulanPSL
- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
- * PURPOSE.
- * See the Mulan PSL v1 for more details.
- * Create: 2019-10-29
- */
-
-package main
-
-import (
- PB "atune/api/profile"
- "atune/common/checker"
- "atune/common/config"
- "atune/common/http"
- "atune/common/log"
- "atune/common/models"
- "atune/common/profile"
- "atune/common/project"
- "atune/common/schedule"
- SVC "atune/common/service"
- "atune/common/sqlstore"
- "atune/common/tuning"
- "atune/common/utils"
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "syscall"
- "time"
-
- "github.com/go-ini/ini"
- "github.com/urfave/cli"
- "google.golang.org/grpc"
- yaml "gopkg.in/yaml.v2"
-)
-
-// Monitor : the body send to monitor service
-type Monitor struct {
- Module string `json:"module"`
- Purpose string `json:"purpose"`
- Field string `json:"field"`
-}
-
-// CollectorPost : the body send to collection service
-type CollectorPost struct {
- Monitors []Monitor `json:"monitors"`
- SampleNum int `json:"sample_num"`
- Pipe string `json:"pipe"`
-}
-
-// RespCollectorPost : the response of collection servie
-type RespCollectorPost struct {
- Path string `json:"path"`
-}
-
-// ClassifyPostBody : the body send to classify service
-type ClassifyPostBody struct {
- Data string `json:"data"`
- ModelPath string `json:"modelpath,omitempty"`
- Model string `json:"model,omitempty"`
-}
-
-// RespClassify : the response of classify model
-type RespClassify struct {
- ResourceLimit string `json:"resource_limit"`
- WorkloadType string `json:"workload_type"`
- Percentage float32 `json:"percentage"`
-}
-
-// ProfileServer : the type impletent the grpc server
-type ProfileServer struct {
- utils.MutexLock
- ConfPath string
- ScriptPath string
- Raw *ini.File
-}
-
-func init() {
- svc := SVC.ProfileService{
- Name: "opt.profile",
- Desc: "opt profile module",
- NewInst: NewProfileServer,
- }
- if err := SVC.AddService(&svc); err != nil {
- fmt.Printf("Failed to load service project : %s\n", err)
- return
- }
-
- log.Info("load profile service successfully\n")
-
-}
-
-// NewProfileServer method new a instance of the grpc server
-func NewProfileServer(ctx *cli.Context, opts ...interface{}) (interface{}, error) {
- defaultConfigFile := path.Join(config.DefaultConfPath, "atuned.cnf")
-
- exist, err := utils.PathExist(defaultConfigFile)
- if err != nil {
- return nil, err
- }
- if !exist {
- return nil, fmt.Errorf("Could not find default config file")
- }
-
- cfg, err := ini.Load(defaultConfigFile)
- if err != nil {
- return nil, fmt.Errorf("Faild to parse %s, %v", defaultConfigFile, err)
- }
-
- return &ProfileServer{
- Raw: cfg,
- }, nil
-}
-
-// RegisterServer method register the grpc service
-func (s *ProfileServer) RegisterServer(server *grpc.Server) error {
- PB.RegisterProfileMgrServer(server, s)
- return nil
-}
-
-// Healthy method, implement SvrService interface
-func (s *ProfileServer) Healthy(opts ...interface{}) error {
- return nil
-}
-
-// Post method send POST to start analysis the workload type
-func (p *ClassifyPostBody) Post() (*RespClassify, error) {
- url := config.GetUrl(config.ClassificationURI)
- response, err := http.Post(url, p)
- if err != nil {
- return nil, err
- }
-
- defer response.Body.Close()
- if response.StatusCode != 200 {
- return nil, fmt.Errorf("online learning faild")
- }
- resBody, err := ioutil.ReadAll(response.Body)
- resPostIns := new(RespClassify)
- err = json.Unmarshal(resBody, resPostIns)
- if err != nil {
- return nil, err
- }
-
- return resPostIns, nil
-}
-
-// Post method send POST to start collection data
-func (c *CollectorPost) Post() (*RespCollectorPost, error) {
- url := config.GetUrl(config.CollectorURI)
- response, err := http.Post(url, c)
- if err != nil {
- return nil, err
- }
-
- defer response.Body.Close()
- if response.StatusCode != 200 {
- return nil, fmt.Errorf("collect data faild")
- }
- resBody, err := ioutil.ReadAll(response.Body)
- resPostIns := new(RespCollectorPost)
- err = json.Unmarshal(resBody, resPostIns)
- if err != nil {
- return nil, err
- }
- return resPostIns, nil
-}
-
-// Profile method set the workload type to effective manual
-func (s *ProfileServer) Profile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ProfileServer) error {
- profileNames := profileInfo.GetName()
-
- profile, ok := profile.LoadFromWorkloadType(profileNames)
-
- if !ok {
- fmt.Println("Failure Load ", profileInfo.GetName())
- return fmt.Errorf("Load profile %s Faild", profileInfo.GetName())
- }
- ch := make(chan *PB.AckCheck)
- ctx, cancel := context.WithCancel(context.Background())
- defer close(ch)
- defer cancel()
-
- go func(ctx context.Context) error {
- for {
- select {
- case value := <-ch:
- stream.Send(value)
- case <-ctx.Done():
- return nil
- }
- }
- return nil
- }(ctx)
-
- if err := profile.RollbackActive(ch); err != nil {
- return err
- }
-
- return nil
-}
-
-// ListWorkload method list support workload
-func (s *ProfileServer) ListWorkload(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ListWorkloadServer) error {
- log.Debug("Begin to inquire all workloads\n")
- workloads := &sqlstore.GetClass{}
- err := sqlstore.GetClasses(workloads)
- if err != nil {
- return err
- }
-
- for _, classProfile := range workloads.Result {
- stream.Send(&PB.ListMessage{WorkloadType: classProfile.Class, ProfileNames: classProfile.ProfileType, Active: strconv.FormatBool(classProfile.Active)})
- }
-
- return nil
-}
-
-// CheckInitProfile method check the system init information
-// like BIOS version, memory balanced...
-func (s *ProfileServer) CheckInitProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_CheckInitProfileServer) error {
- elf := profileInfo.GetName()
-
- rd, err := ioutil.ReadDir(config.DefaultCheckerPath)
- if err != nil {
- return err
- }
-
- ch := make(chan *PB.AckCheck, 0)
- defer close(ch)
- go func() error {
- for {
- select {
- case value, ok := <-ch:
- if ok {
- stream.Send(value)
- continue
- }
- break
- }
- }
- return nil
- }()
-
- elf = strings.Trim(elf, "")
- if elf != "" {
- if exist, _ := utils.PathExist(elf); exist {
- program := checker.ELF{FileName: elf}
- program.Check(ch)
- }
- }
-
- for _, dir := range rd {
- if dir.IsDir() {
- continue
- }
-
- if !strings.HasSuffix(dir.Name(), ".xml") {
- continue
- }
-
- filename := strings.TrimSuffix(dir.Name(), ".xml")
- switch filename {
- case "mem_topo":
- memTopo := checker.MemTopo{Path: path.Join(config.DefaultCheckerPath, dir.Name())}
- memTopo.Check(ch)
- }
- }
-
- time.Sleep(time.Duration(2) * time.Second)
- stream.Send(&PB.AckCheck{Name: "check system finished"})
- return nil
-}
-
-// Analysis method analysis the system traffic load
-func (s *ProfileServer) Analysis(message *PB.AnalysisMessage, stream PB.ProfileMgr_AnalysisServer) error {
- if !s.TryLock() {
- return fmt.Errorf("analysis has been in running")
- }
- defer s.Unlock()
-
- stream.Send(&PB.AckCheck{Name: "1. Analysis system runtime information: CPU Memory IO and Network..."})
-
- npipe, err := utils.CreateNamedPipe()
- if err != nil {
- return fmt.Errorf("create named pipe faild")
- }
-
- defer os.Remove(npipe)
-
- go func() {
- file, _ := os.OpenFile(npipe, os.O_RDONLY, os.ModeNamedPipe)
- reader := bufio.NewReader(file)
-
- scanner := bufio.NewScanner(reader)
-
- for scanner.Scan() {
- line := scanner.Text()
- stream.Send(&PB.AckCheck{Name: line, Status: utils.INFO})
- }
-
- }()
-
- //1. get the dimension structure of the system data to be collected
- collections, err := sqlstore.GetCollections()
- if err != nil {
- log.Errorf("inquery collection tables error: %v", err)
- return err
- }
- // 1.1 send the collect data command to the monitor service
- monitors := make([]Monitor, 0)
- for _, collection := range collections {
- re := regexp.MustCompile(`\{([^}]+)\}`)
- matches := re.FindAllStringSubmatch(collection.Metrics, -1)
- if len(matches) > 0 {
- for _, match := range matches {
- if !s.Raw.Section("system").Haskey(match[1]) {
- return fmt.Errorf("%s is not exist in the system section", match[1])
- }
- value := s.Raw.Section("system").Key(match[1]).Value()
- collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
- }
- }
-
- monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
- monitors = append(monitors, monitor)
- }
-
- sampleNum := s.Raw.Section("server").Key("sample_num").MustInt(20)
- collectorBody := new(CollectorPost)
- collectorBody.SampleNum = sampleNum
- collectorBody.Monitors = monitors
- collectorBody.Pipe = npipe
-
- respCollectPost, err := collectorBody.Post()
- if err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error()})
- return err
- }
-
- //2. send the collected data to the model for completion type identification
- body := new(ClassifyPostBody)
- body.Data = respCollectPost.Path
- body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")
-
- if message.GetModel() != "" {
- body.Model = message.GetModel()
- }
- respPostIns, err := body.Post()
-
- if err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error()})
- return err
- }
-
- workloadType := respPostIns.WorkloadType
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", workloadType)})
-
- //3. judge the workload type is exist in the database
- classProfile := &sqlstore.GetClass{Class: workloadType}
- if err := sqlstore.GetClasses(classProfile); err != nil {
- log.Errorf("inquery workload type table faild %v", err)
- return fmt.Errorf("inquery workload type table faild %v", err)
- }
- if len(classProfile.Result) == 0 {
- log.Errorf("%s is not exist in the table", workloadType)
- return fmt.Errorf("%s is not exist in the table", workloadType)
- }
-
- // the workload type is already actived
- if classProfile.Result[0].Active {
- log.Infof("analysis result %s is the same with current active workload type", workloadType)
- return nil
- }
-
- //4. inquery the support app of the workload type
- classApps := &sqlstore.GetClassApp{Class: workloadType}
- err = sqlstore.GetClassApps(classApps)
- if err != nil {
- log.Errorf("inquery support app depend on class error: %v", err)
- return err
- }
- if len(classApps.Result) == 0 {
- return fmt.Errorf("class %s is not exist in the tables", workloadType)
- }
- apps := classApps.Result[0].Apps
- log.Infof("workload %s support app: %s", workloadType, apps)
- log.Infof("workload %s resource limit: %s, cluster result resource limit: %s", workloadType, apps, respPostIns.ResourceLimit)
-
- stream.Send(&PB.AckCheck{Name: "\n 3. Build the best resource model..."})
-
- //5. get the profile type depend on the workload type
- profileType := classProfile.Result[0].ProfileType
- profileNames := strings.Split(profileType, ",")
- if len(profileNames) == 0 {
- log.Errorf("No profile or invaild profiles were specified.")
- return fmt.Errorf("No profile or invaild profiles were specified")
- }
-
- //6. get the profile info depend on the profile type
- log.Infof("the resource model of the profile type is %s", profileType)
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 4. Match profile: %s", profileType)})
- pro, _ := profile.Load(profileNames)
- pro.SetWorkloadType(workloadType)
-
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 5. bengin to set static profile")})
- log.Infof("bengin to set static profile")
-
- //static profile setting
- ch := make(chan *PB.AckCheck, 0)
- go func() error {
- for {
- select {
- case value, ok := <-ch:
- if ok {
- stream.Send(value)
- continue
- }
- break
- }
- }
- return nil
- }()
- pro.RollbackActive(ch)
-
- rules := &sqlstore.GetRuleTuned{Class: workloadType}
- if err := sqlstore.GetRuleTuneds(rules); err != nil {
- return err
- }
-
- if len(rules.Result) < 1 {
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("Completed optimization, please restart application!")})
- log.Info("no rules to tuned")
- return nil
- }
-
- log.Info("begin to dynamic tunning depending on rules")
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 6. bengin to set dynamic profile")})
- if err := tuning.RuleTuned(workloadType); err != nil {
- return err
- }
-
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("Completed optimization, please restart application!")})
- return nil
-}
-
-// Tuning method calling the bayes search method to tuned parameters
-func (s *ProfileServer) Tuning(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_TuningServer) error {
- //dynamic profle setting
- data := profileInfo.GetName()
- fmt.Println(data)
-
- var byteData []byte = []byte(data)
- project := project.YamlPrj{}
- if err := yaml.Unmarshal(byteData, &project); err != nil {
- return err
- }
-
- log.Info("begin to dynamic optimizer search")
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("bengin to dynamic optimizer search")})
-
- ch := make(chan *PB.AckCheck, 0)
- go func() error {
- for {
- select {
- case value, ok := <-ch:
- if ok {
- stream.Send(value)
- continue
- }
- break
- }
- }
- return nil
- }()
-
- optimizer := tuning.Optimizer{Prj: &project}
- err := optimizer.DynamicTuned(ch)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-/*
-UpgradeProfile method update the db file
-*/
-func (s *ProfileServer) UpgradeProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_UpgradeProfileServer) error {
- log.Debug("Begin to upgrade profiles\n")
- currenDbPath := path.Join(config.DatabasePath, config.DatabaseName)
- newDbPath := profileInfo.GetName()
-
- exist, err := utils.PathExist(config.DefaultTempPath)
- if err != nil {
- return err
- }
- if !exist {
- os.MkdirAll(config.DefaultTempPath, os.ModePerm)
- }
- timeUnix := strconv.FormatInt(time.Now().Unix(), 10) + ".db"
- tempFile := path.Join(config.DefaultTempPath, timeUnix)
-
- if err := utils.CopyFile(tempFile, currenDbPath); err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
- return nil
- }
-
- if err := utils.CopyFile(currenDbPath, newDbPath); err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
- return nil
- }
-
- if err := sqlstore.Reload(currenDbPath); err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error(), Status: utils.FAILD})
- return nil
- }
-
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("upgrade success"), Status: utils.SUCCESS})
- return nil
-}
-
-/*
-InfoProfile method display the content of the specified workload type
-*/
-func (s *ProfileServer) InfoProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_InfoProfileServer) error {
- workloadType := profileInfo.GetName()
- classProfile := &sqlstore.GetClass{Class: workloadType}
- err := sqlstore.GetClasses(classProfile)
- if err != nil {
- log.Errorf("inquery class_profile table faild")
- return fmt.Errorf("inquery class_profile table faild")
- }
-
- if len(classProfile.Result) == 0 {
- log.Errorf("%s is not exist in the class_profile table", workloadType)
- return fmt.Errorf("%s is not exist in the class_profile table", workloadType)
- }
-
- profileType := classProfile.Result[0].ProfileType
- profileNames := strings.Split(profileType, ",")
- for _, name := range profileNames {
- name = strings.Trim(name, " ")
- context, _ := sqlstore.GetContext(name)
- context = "\n*** " + name + ":\n" + context
- stream.Send(&PB.ProfileInfo{Name: context})
- }
-
- return nil
-}
-
-/*
-CheckActiveProfile method check current active profile is effective
-*/
-func (s *ProfileServer) CheckActiveProfile(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_CheckActiveProfileServer) error {
- log.Debug("Begin to check active profiles\n")
- profiles := &sqlstore.GetClass{Active: true}
- err := sqlstore.GetClasses(profiles)
- if err != nil {
- return err
- }
- if len(profiles.Result) != 1 {
- return fmt.Errorf("No active profile or more than 1 active profile")
- }
-
- workloadType := profiles.Result[0].Class
- profile, ok := profile.LoadFromWorkloadType(workloadType)
-
- if !ok {
- log.WithField("profile", workloadType).Errorf("Load profile %s Faild", workloadType)
- return fmt.Errorf("Load workload type %s Faild", workloadType)
- }
-
- ch := make(chan *PB.AckCheck, 0)
- defer close(ch)
- go func() error {
- for {
- select {
- case value, ok := <-ch:
- if ok {
- stream.Send(value)
- continue
- }
- break
- }
- return nil
- }
- return nil
- }()
-
- if err := profile.Check(ch); err != nil {
- return err
- }
-
- return nil
-}
-
-// ProfileRollback method rollback the profile to init state
-func (s *ProfileServer) ProfileRollback(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_ProfileRollbackServer) error {
-
- profileLogs, err := sqlstore.GetProfileLogs()
- if err != nil {
- return err
- }
-
- if len(profileLogs) < 1 {
- stream.Send(&PB.AckCheck{Name: "no profile need to rollback"})
- return nil
- }
-
- sort.Slice(profileLogs, func(i, j int) bool {
- return profileLogs[i].ID > profileLogs[j].ID
- })
-
- //static profile setting
- ch := make(chan *PB.AckCheck, 0)
- go func() error {
- for {
- select {
- case value, ok := <-ch:
- if ok {
- stream.Send(value)
- continue
- }
- break
- }
- return nil
- }
- return nil
- }()
-
- for _, pro := range profileLogs {
- log.Infof("begin to restore profile id: %s", pro.ID)
- profileInfo := profile.HistoryProfile{}
- profileInfo.Load(pro.Context)
- profileInfo.Resume(ch)
-
- // delete profile log after restored
- if err := sqlstore.DelProfileLogByID(pro.ID); err != nil {
- return err
- }
- //delete backup dir
- if err := os.RemoveAll(pro.BackupPath); err != nil {
- return err
- }
-
- // update active profile after restored
- if err := sqlstore.ActiveProfile(pro.ProfileID); err != nil {
- return nil
- }
- }
-
- if err := sqlstore.InActiveProfile(); err != nil {
- return nil
- }
-
- return nil
-}
-
-/*
-Collection method call collection script to collect system data.
-*/
-func (s *ProfileServer) Collection(message *PB.CollectFlag, stream PB.ProfileMgr_CollectionServer) error {
- classApps := &sqlstore.GetClassApp{Class: message.GetType()}
- err := sqlstore.GetClassApps(classApps)
- if err != nil {
- return err
- }
- if len(classApps.Result) == 0 {
- return fmt.Errorf("workload type %s is not exist, please use define command first", message.GetType())
- }
-
- exist, err := utils.PathExist(message.GetOutputPath())
- if err != nil {
- return err
- }
- if !exist {
- return fmt.Errorf("output_path %s is not exist", message.GetOutputPath())
- }
-
- if err := utils.InterfaceByName(message.GetNetwork()); err != nil {
- return err
- }
-
- if err := utils.DiskByName(message.GetBlock()); err != nil {
- return err
- }
-
- collector := path.Join(config.DefaultCollectorPath, "collect_training_data.sh")
- script := make([]string, 0)
-
- script = append(script, collector)
- script = append(script, message.GetWorkload())
- script = append(script, strconv.FormatInt(message.GetDuration(), 10))
- script = append(script, strconv.FormatInt(message.GetInterval(), 10))
- script = append(script, message.GetOutputPath())
- script = append(script, message.GetBlock())
- script = append(script, message.GetNetwork())
- script = append(script, message.GetType())
-
- newScript := strings.Join(script, " ")
- cmd := exec.Command("sudo", "sh", "-c", newScript)
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
-
- stdout, err := cmd.StdoutPipe()
- stderr, err := cmd.StderrPipe()
-
- ctx := stream.Context()
- go func() {
- for {
- select {
- case <-ctx.Done():
- syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
- return
- }
- }
- }()
-
- go func() {
- scanner := bufio.NewScanner(stdout)
- for scanner.Scan() {
- line := scanner.Text()
- stream.Send(&PB.AckCheck{Name: line})
- }
- }()
-
- go func() {
- scanner := bufio.NewScanner(stderr)
- for scanner.Scan() {
- line := scanner.Text()
- stream.Send(&PB.AckCheck{Name: line})
- }
- }()
-
- err = cmd.Start()
- if err != nil {
- log.Error(err)
- return err
- }
-
- err = cmd.Wait()
-
- if err != nil {
- log.Error(err)
- return err
- }
-
- return nil
-}
-
-/*
-Training method train the collected data to generate the model
-*/
-func (s *ProfileServer) Training(message *PB.TrainMessage, stream PB.ProfileMgr_TrainingServer) error {
- DataPath := message.GetDataPath()
- OutputPath := message.GetOutputPath()
-
- trainBody := new(models.Training)
- trainBody.DataPath = DataPath
- trainBody.OutputPath = OutputPath
- trainBody.ModelPath = path.Join(config.DefaultAnalysisPath, "models")
-
- success, err := trainBody.Post()
- if err != nil {
- return err
- }
- if success {
- stream.Send(&PB.AckCheck{Name: "training the self collect data success"})
- return nil
- }
-
- stream.Send(&PB.AckCheck{Name: "training the self collect data faild"})
- return nil
-}
-
-// Charaterization method will be deprecate in the future
-func (s *ProfileServer) Charaterization(profileInfo *PB.ProfileInfo, stream PB.ProfileMgr_CharaterizationServer) error {
- stream.Send(&PB.AckCheck{Name: "1. Analysis system runtime information: CPU Memory IO and Network..."})
-
- npipe, err := utils.CreateNamedPipe()
- if err != nil {
- return fmt.Errorf("create named pipe faild")
- }
-
- defer os.Remove(npipe)
-
- go func() {
- file, _ := os.OpenFile(npipe, os.O_RDONLY, os.ModeNamedPipe)
- reader := bufio.NewReader(file)
-
- scanner := bufio.NewScanner(reader)
-
- for scanner.Scan() {
- line := scanner.Text()
- stream.Send(&PB.AckCheck{Name: line, Status: utils.INFO})
- }
-
- }()
-
- //1. get the dimension structure of the system data to be collected
- collections, err := sqlstore.GetCollections()
- if err != nil {
- log.Errorf("inquery collection tables error: %v", err)
- return err
- }
- // 1.1 send the collect data command to the monitor service
- monitors := make([]Monitor, 0)
- for _, collection := range collections {
- re := regexp.MustCompile(`\{([^}]+)\}`)
- matches := re.FindAllStringSubmatch(collection.Metrics, -1)
- if len(matches) > 0 {
- for _, match := range matches {
- if !s.Raw.Section("system").Haskey(match[1]) {
- return fmt.Errorf("%s is not exist in the system section", match[1])
- }
- value := s.Raw.Section("system").Key(match[1]).Value()
- collection.Metrics = re.ReplaceAllString(collection.Metrics, value)
- }
- }
-
- monitor := Monitor{Module: collection.Module, Purpose: collection.Purpose, Field: collection.Metrics}
- monitors = append(monitors, monitor)
- }
-
- collectorBody := new(CollectorPost)
- collectorBody.SampleNum = 5
- collectorBody.Monitors = monitors
- collectorBody.Pipe = npipe
-
- respCollectPost, err := collectorBody.Post()
- if err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error()})
- return err
- }
-
- //2. send the collected data to the model for completion type identification
- body := new(ClassifyPostBody)
- body.Data = respCollectPost.Path
- body.ModelPath = path.Join(config.DefaultAnalysisPath, "models")
-
- respPostIns, err := body.Post()
-
- if err != nil {
- stream.Send(&PB.AckCheck{Name: err.Error()})
- return err
- }
-
- workloadType := respPostIns.WorkloadType
- stream.Send(&PB.AckCheck{Name: fmt.Sprintf("\n 2. Current System Workload Characterization is %s", workloadType)})
- return nil
-
-}
-
-// Define method user define workload type and profile
-func (s *ProfileServer) Define(ctx context.Context, message *PB.DefineMessage) (*PB.Ack, error) {
- workloadType := message.GetWorkloadType()
- profileName := message.GetProfileName()
- content := string(message.GetContent())
-
- workloadTypeExist, err := sqlstore.ExistWorkloadType(workloadType)
- if err != nil {
- return &PB.Ack{}, err
- }
- if workloadTypeExist {
- return &PB.Ack{Status: fmt.Sprintf("%s is already exist", workloadType)}, nil
- }
-
- profileExist, err := sqlstore.ExistProfile(profileName)
- if err != nil {
- return &PB.Ack{}, err
- }
-
- if profileExist {
- return &PB.Ack{Status: fmt.Sprintf("%s is already exist", profileName)}, nil
- }
-
- if err := sqlstore.InsertClassApps(&sqlstore.ClassApps{Class: workloadType, Deletable: true}); err != nil {
- return &PB.Ack{}, err
- }
- if err := sqlstore.InsertClassProfile(&sqlstore.ClassProfile{Class: workloadType, ProfileType: profileName, Active: false}); err != nil {
- return &PB.Ack{}, err
- }
-
- if err := sqlstore.InsertProfile(&sqlstore.Profile{ProfileType: profileName, ProfileInformation: content}); err != nil {
- return &PB.Ack{}, err
- }
-
- return &PB.Ack{Status: "OK"}, nil
-}
-
-// Delete method delete the self define workload type from database
-func (s *ProfileServer) Delete(ctx context.Context, message *PB.DefineMessage) (*PB.Ack, error) {
- workloadType := message.GetWorkloadType()
-
- classApps := &sqlstore.GetClassApp{Class: workloadType}
- err := sqlstore.GetClassApps(classApps)
- if err != nil {
- return &PB.Ack{}, err
- }
-
- log.Infof("the result length: %d, query the classapp table of workload: %s", len(classApps.Result), workloadType)
- if len(classApps.Result) != 1 {
- return &PB.Ack{Status: fmt.Sprintf("workload type %s may be not exist in the table", workloadType)}, nil
- }
-
- classApp := classApps.Result[0]
- if classApp.Deletable != true {
- return &PB.Ack{Status: "only self defined workload type can be deleted"}, nil
- }
-
- if err := sqlstore.DeleteClassApps(workloadType); err != nil {
- return &PB.Ack{}, err
- }
-
- // get the profile type from the classprofile table
- classProfile := &sqlstore.GetClass{Class: workloadType}
- if err := sqlstore.GetClasses(classProfile); err != nil {
- log.Errorf("inquery workload type table faild %v", err)
- return &PB.Ack{}, fmt.Errorf("inquery workload type table faild %v", err)
- }
- if len(classProfile.Result) == 0 {
- log.Errorf("%s is not exist in the table", workloadType)
- return &PB.Ack{}, fmt.Errorf("%s is not exist in the table", workloadType)
- }
-
- profileType := classProfile.Result[0].ProfileType
- profileNames := strings.Split(profileType, ",")
- if len(profileNames) == 0 {
- log.Errorf("No profile or invaild profiles were specified.")
- return &PB.Ack{}, fmt.Errorf("No profile or invaild profiles were specified")
- }
-
- // delete profile depend the profiletype
- for _, profileName := range profileNames {
- if err := sqlstore.DeleteProfile(profileName); err != nil {
- log.Errorf("delete item from profile table faild %v ", err)
- }
- }
-
- // delete classprofile depend the workloadType
- if err := sqlstore.DeleteClassProfile(workloadType); err != nil {
- log.Errorf("delete item from classprofile tabble faild.")
- return &PB.Ack{}, err
- }
- return &PB.Ack{Status: "OK"}, nil
-}
-
-// Update method update the content of the specified workload type from database
-func (s *ProfileServer) Update(ctx context.Context, message *PB.DefineMessage) (*PB.Ack, error) {
- workloadType := message.GetWorkloadType()
- profileName := message.GetProfileName()
- content := string(message.GetContent())
-
- workloadTypeExist, err := sqlstore.ExistWorkloadType(workloadType)
- if err != nil {
- return &PB.Ack{}, err
- }
- if !workloadTypeExist {
- return &PB.Ack{Status: fmt.Sprintf("workload type %s is not exist in the table", workloadType)}, nil
- }
-
- // get the profile type from the classprofile table
- classProfile := &sqlstore.GetClass{Class: workloadType}
- if err := sqlstore.GetClasses(classProfile); err != nil {
- log.Errorf("inquery workload type table faild %v", err)
- return &PB.Ack{}, fmt.Errorf("inquery workload type table faild %v", err)
- }
- if len(classProfile.Result) == 0 {
- log.Errorf("%s is not exist in the table", workloadType)
- return &PB.Ack{}, fmt.Errorf("%s is not exist in the table", workloadType)
- }
-
- profileType := classProfile.Result[0].ProfileType
- profileNames := strings.Split(profileType, ",")
- if len(profileNames) == 0 {
- log.Errorf("No profile or invaild profiles were specified.")
- return &PB.Ack{}, fmt.Errorf("no profile exist corresponding to workload type")
- }
-
- exist := false
- for _, profile := range profileNames {
- if profileName == strings.TrimSpace(profile) {
- exist = true
- break
- }
- }
- if !exist {
- return &PB.Ack{}, fmt.Errorf("profile name %s is exist corresponding to workload type %s", profileName, workloadType)
- }
-
- if err := sqlstore.UpdateProfile(&sqlstore.Profile{ProfileType: profileName, ProfileInformation: content}); err != nil {
- return &PB.Ack{}, err
- }
- return &PB.Ack{Status: "OK"}, nil
-}
-
-/*
- * schedule cpu/irq/numa ...
- */
-func (s *ProfileServer) Schedule(message *PB.ScheduleMessage, stream PB.ProfileMgr_ScheduleServer) error {
- _ = message.GetApp()
- Type := message.GetType()
- Strategy := message.GetStrategy()
-
- scheduler := schedule.GetScheduler()
- scheduler.Schedule(Type, Strategy, true)
-
- return nil
-}
diff --git a/openeuler-A-Tune-v0.2.tar.gz b/openeuler-A-Tune-v0.2.tar.gz
new file mode 100644
index 0000000..fa12324
Binary files /dev/null and b/openeuler-A-Tune-v0.2.tar.gz differ
diff --git a/scripts/ethtool/set.sh b/scripts/ethtool/set.sh
deleted file mode 100755
index 49f944f..0000000
--- a/scripts/ethtool/set.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-ethtool $*
-exit $?
diff --git a/scripts/hugepage/get.sh b/scripts/hugepage/get.sh
deleted file mode 100755
index 61a2eb5..0000000
--- a/scripts/hugepage/get.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/sh
-
-MYPROF_PATH=~/.bash_tlbprof
-
-HugePages=`grep HugePages_Total /proc/meminfo | awk '{print $2}'`
-if [ ${HugePages} = 0 ]; then
- rm -f ${MYPROF_PATH}
- echo "0" && exit 0
-fi
-
-[ -f ${MYPROF_PATH} ] && echo "1" && exit 0
-
-echo "0" && exit 0
diff --git a/scripts/hugepage/set.sh b/scripts/hugepage/set.sh
deleted file mode 100755
index d060791..0000000
--- a/scripts/hugepage/set.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/bin/sh
-
-SCRIPT=$(basename $0)
-
-if [ $# != 1 ]; then
- echo "Usage: ${SCRIPT} 0:disable or 1:enable"
- exit 1
-fi
-
-PROF_PATH=~/.bash_profile
-MYPROF_PATH=~/.bash_tlbprof
-
-HugePages=`grep HugePages_Total /proc/meminfo | awk '{print $2}'`
-if [ ${HugePages} = 0 -o $1 = 0 ]; then
- rm -f ${MYPROF_PATH}
- exit 0
-fi
-
-echo "export HUGETLB_MORECORE=yes" > ${MYPROF_PATH}
-[ $? != 0 ] && exit 2
-echo "export LD_PRELOAD=/usr/lib64/libhugetlbfs.so" >> ${MYPROF_PATH}
-[ $? != 0 ] && exit 2
-
-grep tlbprof ${PROF_PATH} > /dev/null
-if [ $? != 0 ]; then
- echo "if [ -f ${MYPROF_PATH} ]; then" >> ${PROF_PATH}
- [ $? != 0 ] && exit 3
- echo " . ${MYPROF_PATH}" >> ${PROF_PATH}
- [ $? != 0 ] && exit 3
- echo "fi" >> ${PROF_PATH}
- [ $? != 0 ] && exit 3
-fi
-
-exit 0
diff --git a/scripts/ifconfig/set.sh b/scripts/ifconfig/set.sh
deleted file mode 100755
index a1a24cb..0000000
--- a/scripts/ifconfig/set.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-ifconfig $*
-exit $?
diff --git a/scripts/openssl_hpre/hisi_openssl.cnf b/scripts/openssl_hpre/hisi_openssl.cnf
deleted file mode 100755
index 868899c..0000000
--- a/scripts/openssl_hpre/hisi_openssl.cnf
+++ /dev/null
@@ -1,6 +0,0 @@
-[LogSection]
-debug_level=none
-
-[QueueSection]
-queue_number=6
-is_soft=yes
diff --git a/scripts/openssl_hpre/openssl.cnf b/scripts/openssl_hpre/openssl.cnf
deleted file mode 100644
index 3080961..0000000
--- a/scripts/openssl_hpre/openssl.cnf
+++ /dev/null
@@ -1,10 +0,0 @@
-openssl_conf = openssl_def
-[openssl_def]
-engines = engine_section
-[engine_section]
-hpre2 = hpre2_section
-[hpre2_section]
-engine_id = hpre2
-dynamic_path = /usr/lib64/engines-1.1/hpre2.so
-default_algorithms = ALL
-
diff --git a/scripts/openssl_hpre/set.sh b/scripts/openssl_hpre/set.sh
deleted file mode 100644
index b0625bc..0000000
--- a/scripts/openssl_hpre/set.sh
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/bin/sh
-
-SCRIPT=$(basename $0)
-DIR=$(dirname $0)
-#echo $SCRIPT
-#echo $DIR
-
-
-HPRE_HOME_PATH=$(cd "$(dirname "$0")";pwd)
-echo $HPRE_HOME_PATH
-
-if [ $# != 1 ]; then
- echo "Usage: ${SCRIPT} 1:enable or 0: disable"
- exit 1
-fi
-
-#echo $1
-
-if [ $1 == "1" ]; then
- #echo "Enable hpre"
-
-
- if lspci | grep -q 'HPRE' ; then
- echo " [check] This machine support HPRE device!"
- else
- echo "\033[31m This Machine can not support HPRE, try to upgrade bios to version 3.24.01 and re-power on the machine \033[0m"
- exit 1
- fi
-
- if openssl version | grep -q 'OpenSSL' ; then
- echo " [check] The openssl is installed, make sure its version is newer than 1.1.1"
- else
- echo "\033[31m NO openssl is installed, please installed it firstly! \033[31m"
- exit 1
- fi
-
- if lsmod | grep -q 'hisi_hpre' ; then
- echo " [check] The hpre kernel driver is detected"
- else
- echo "\033[31m No hpre kernel driver is detected, install the hpre driver firstlly! \033[31m"
- exit 1
- fi
-
- if ls /usr/lib64/engines-1.1/ | grep -q "hpre2.so" ; then
- echo " [check] Detect the hpre2 engine in the openssl engine libs"
- else
- echo "\033[31m No hpre2 engine in the openssl engine libs, install hpre2 engine into the openssl engine libs \033[31m"
- exit 1
- fi
-
- if ls /usr/lib64 | grep -q "libwd.*" ; then
- echo " [check] Detect the Union Acceleration Framework libwd.* in the /usr/lib64"
- else
- echo "\033[31m No Union Acceleration Framework is detected, install it to use hpre! \033[31m"
- exit 1
- fi
-
- orig_openssl_conf=$(openssl version -d | awk '{print $2}' | sed 's/\"//g')
- if [ ! -d "$orig_openssl_conf" ]; then
- echo "Failed to Get orig openssl conf file: $orig_openssl_conf"
- fi
-
- orig_openssl_conf=$orig_openssl_conf"/openssl.cnf"
-
- echo $orig_openssl_conf
-
- cat ${HPRE_HOME_PATH}/openssl.cnf > ${HPRE_HOME_PATH}/openssl_hpre.cnf
- cat $orig_openssl_conf >> ${HPRE_HOME_PATH}/openssl_hpre.cnf
-
- export HISI_CONF_ENV=${HPRE_HOME_PATH}
- export OPENSSL_CONF=${HPRE_HOME_PATH}/openssl_hpre.cnf
-
- sed -i '/export OPENSSL_CONF=/d' /etc/profile
- sed -i '/export HISI_CONF_ENV=/d' /etc/profile
-
- echo "export HISI_CONF_ENV=${HPRE_HOME_PATH}" >> /etc/profile
- echo "export OPENSSL_CONF=${HPRE_HOME_PATH}/openssl_hpre.cnf" >> /etc/profile
-
- #alias openssl='HISI_CONF_ENV=${HPRE_HOME_PATH} OPENSSL_CONF=${HPRE_HOME_PATH}/openssl.cnf openssl'
-
- source /etc/profile
-
- echo -e "\033[31m Please execute cmd 'source /etc/profile' and restart application (e.g. nginx) to make hpre in use! \033[0m"
-
-
-else
- echo "Disable hpre"
-
- sed -i '/export OPENSSL_CONF=/d' /etc/profile
- sed -i '/export HISI_CONF_ENV=/d' /etc/profile
- #sed -e ''
-
- echo "export HISI_CONF_ENV=" >> /etc/profile
- echo "export OPENSSL_CONF=" >> /etc/profile
-
- #source ${HPRE_HOME_PATH}/nohpre_env.sh
-fi
-
-exit 0
-
-
-
diff --git a/scripts/prefetch/get.sh b/scripts/prefetch/get.sh
deleted file mode 100755
index 57ac030..0000000
--- a/scripts/prefetch/get.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-
-SCRIPT=$(basename $0)
-SCRIPT_PATH=$(cd "$(dirname "$0")";pwd)
-
-if [ $# != 0 ]; then
- echo "Usage: ${SCRIPT}"
- exit 1
-fi
-
-lsmod | grep prefetch_tunning &> /dev/null
-[ $? != 0 ] && echo "reset" && exit 0
-
-policy=$(cat /sys/class/misc/prefetch/policy | awk '{print $2}'| sort -u)
-case "$policy" in
- "15")
- echo "on"
- ;;
- "0")
- echo "off"
- ;;
- *)
- echo "reset"
- ;;
-esac
-
-exit 0
diff --git a/scripts/prefetch/set.sh b/scripts/prefetch/set.sh
deleted file mode 100755
index d3f8a0f..0000000
--- a/scripts/prefetch/set.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/sh
-
-SCRIPT=$(basename $0)
-SCRIPT_PATH=$(cd "$(dirname "$0")";pwd)
-
-if [ $# != 1 ]; then
- echo "Usage: ${SCRIPT} on or off"
- exit 1
-fi
-
-lsmod | grep prefetch_tunning &> /dev/null
-uninstall=$?
-
-case "$1" in
- "on")
- policy=15
- ;;
- "off")
- policy=0
- ;;
- "reset")
- if [ ${uninstall} = 0 ]; then
- rmmod prefetch_tunning
- fi
- exit 0
- ;;
- *)
- exit 2
- ;;
-esac
-
-if [ ${uninstall} != 0 ]; then
- modprobe prefetch_tunning
- [ $? != 0 ] && exit 3
-fi
-
-echo ${policy} > /sys/class/misc/prefetch/policy
-[ $? != 0 ] && exit 4
-
-exit 0
diff --git a/scripts/swapoff/set.sh b/scripts/swapoff/set.sh
deleted file mode 100755
index 5888b5c..0000000
--- a/scripts/swapoff/set.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-swapoff $*
-exit $?
diff --git a/tools/example_conf.py b/tools/example_conf.py
deleted file mode 100755
index 1349216..0000000
--- a/tools/example_conf.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Tool to generate an example of profile configuration.
-"""
-
-import sys
-sys.path.insert(0, "./../analysis/")
-from plugin.plugin import CPI
-
-
-print("#")
-print("# example of atuned profile configuration")
-print("#\n")
-
-global_sections = (("main", "list it's parent profile"),
- ("tip", "the recommended optimization, which should be performed manunaly"),
- ("check", "check the environment"))
-
-for i in global_sections:
- print("[{}]".format(i[0]))
- print("# {}".format(i[1]))
- print("\n")
-
-cpi = CPI()
-cpis = cpi.get_configurators()
-for i in cpis:
- if i.module() == i.submod():
- print("[{}]".format(i.module().lower()))
- else:
- print("[{}.{}]".format(i.module().lower(), i.submod().lower()))
- print("# {}".format(i.__doc__.lower()))
- print("\n")
diff --git a/tools/plugin_api_man.py b/tools/plugin_api_man.py
deleted file mode 100755
index fbdfc23..0000000
--- a/tools/plugin_api_man.py
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/usr/bin/python3
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019 Huawei Technologies Co., Ltd.
-# A-Tune is licensed under the Mulan PSL v1.
-# You can use this software according to the terms and conditions of the Mulan PSL v1.
-# You may obtain a copy of Mulan PSL v1 at:
-# http://license.coscl.org.cn/MulanPSL
-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-# PURPOSE.
-# See the Mulan PSL v1 for more details.
-# Create: 2019-10-29
-
-"""
-Temporary tool to generate the api help info, will be replaced by Sphinx.
-"""
-
-import sys
-sys.path.insert(0, "./../analysis/")
-from plugin.plugin import CPI, MPI
-
-
-print("The CPI & MPI api manual")
-print("========================\n")
-
-cpi = CPI()
-help(cpi)
-
-cpis = cpi.get_configurators()
-for i in cpis:
- help(i)
-
-mpi = MPI()
-help(mpi)
-
-mpis = mpi.get_monitors()
-for i in mpis:
- help(i)
diff --git a/vendor/github.com/antlr/antlr4/LICENSE.txt b/vendor/github.com/antlr/antlr4/LICENSE.txt
deleted file mode 100644
index 2042d1b..0000000
--- a/vendor/github.com/antlr/antlr4/LICENSE.txt
+++ /dev/null
@@ -1,52 +0,0 @@
-[The "BSD 3-clause license"]
-Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. 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.
- 3. Neither the name of the copyright holder 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 THE AUTHOR ``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 THE AUTHOR 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.
-
-=====
-
-MIT License for codepointat.js from https://git.io/codepointat
-MIT License for fromcodepoint.js from https://git.io/vDW1m
-
-Copyright Mathias Bynens
-
-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.
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn.go
deleted file mode 100644
index 1592212..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-var ATNInvalidAltNumber int
-
-type ATN struct {
- // DecisionToState is the decision points for all rules, subrules, optional
- // blocks, ()+, ()*, etc. Used to build DFA predictors for them.
- DecisionToState []DecisionState
-
- // grammarType is the ATN type and is used for deserializing ATNs from strings.
- grammarType int
-
- // lexerActions is referenced by action transitions in the ATN for lexer ATNs.
- lexerActions []LexerAction
-
- // maxTokenType is the maximum value for any symbol recognized by a transition in the ATN.
- maxTokenType int
-
- modeNameToStartState map[string]*TokensStartState
-
- modeToStartState []*TokensStartState
-
- // ruleToStartState maps from rule index to starting state number.
- ruleToStartState []*RuleStartState
-
- // ruleToStopState maps from rule index to stop state number.
- ruleToStopState []*RuleStopState
-
- // ruleToTokenType maps the rule index to the resulting token type for lexer
- // ATNs. For parser ATNs, it maps the rule index to the generated bypass token
- // type if ATNDeserializationOptions.isGenerateRuleBypassTransitions was
- // specified, and otherwise is nil.
- ruleToTokenType []int
-
- states []ATNState
-}
-
-func NewATN(grammarType int, maxTokenType int) *ATN {
- return &ATN{
- grammarType: grammarType,
- maxTokenType: maxTokenType,
- modeNameToStartState: make(map[string]*TokensStartState),
- }
-}
-
-// NextTokensInContext computes the set of valid tokens that can occur starting
-// in state s. If ctx is nil, the set of tokens will not include what can follow
-// the rule surrounding s. In other words, the set will be restricted to tokens
-// reachable staying within the rule of s.
-func (a *ATN) NextTokensInContext(s ATNState, ctx RuleContext) *IntervalSet {
- return NewLL1Analyzer(a).Look(s, nil, ctx)
-}
-
-// NextTokensNoContext computes the set of valid tokens that can occur starting
-// in s and staying in same rule. Token.EPSILON is in set if we reach end of
-// rule.
-func (a *ATN) NextTokensNoContext(s ATNState) *IntervalSet {
- if s.GetNextTokenWithinRule() != nil {
- return s.GetNextTokenWithinRule()
- }
-
- s.SetNextTokenWithinRule(a.NextTokensInContext(s, nil))
- s.GetNextTokenWithinRule().readOnly = true
-
- return s.GetNextTokenWithinRule()
-}
-
-func (a *ATN) NextTokens(s ATNState, ctx RuleContext) *IntervalSet {
- if ctx == nil {
- return a.NextTokensNoContext(s)
- }
-
- return a.NextTokensInContext(s, ctx)
-}
-
-func (a *ATN) addState(state ATNState) {
- if state != nil {
- state.SetATN(a)
- state.SetStateNumber(len(a.states))
- }
-
- a.states = append(a.states, state)
-}
-
-func (a *ATN) removeState(state ATNState) {
- a.states[state.GetStateNumber()] = nil // Just free the memory; don't shift states in the slice
-}
-
-func (a *ATN) defineDecisionState(s DecisionState) int {
- a.DecisionToState = append(a.DecisionToState, s)
- s.setDecision(len(a.DecisionToState) - 1)
-
- return s.getDecision()
-}
-
-func (a *ATN) getDecisionState(decision int) DecisionState {
- if len(a.DecisionToState) == 0 {
- return nil
- }
-
- return a.DecisionToState[decision]
-}
-
-// getExpectedTokens computes the set of input symbols which could follow ATN
-// state number stateNumber in the specified full parse context ctx and returns
-// the set of potentially valid input symbols which could follow the specified
-// state in the specified context. This method considers the complete parser
-// context, but does not evaluate semantic predicates (i.e. all predicates
-// encountered during the calculation are assumed true). If a path in the ATN
-// exists from the starting state to the RuleStopState of the outermost context
-// without Matching any symbols, Token.EOF is added to the returned set.
-//
-// A nil ctx defaults to ParserRuleContext.EMPTY.
-//
-// It panics if the ATN does not contain state stateNumber.
-func (a *ATN) getExpectedTokens(stateNumber int, ctx RuleContext) *IntervalSet {
- if stateNumber < 0 || stateNumber >= len(a.states) {
- panic("Invalid state number.")
- }
-
- s := a.states[stateNumber]
- following := a.NextTokens(s, nil)
-
- if !following.contains(TokenEpsilon) {
- return following
- }
-
- expected := NewIntervalSet()
-
- expected.addSet(following)
- expected.removeOne(TokenEpsilon)
-
- for ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {
- invokingState := a.states[ctx.GetInvokingState()]
- rt := invokingState.GetTransitions()[0]
-
- following = a.NextTokens(rt.(*RuleTransition).followState, nil)
- expected.addSet(following)
- expected.removeOne(TokenEpsilon)
- ctx = ctx.GetParent().(RuleContext)
- }
-
- if following.contains(TokenEpsilon) {
- expected.addOne(TokenEOF)
- }
-
- return expected
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config.go
deleted file mode 100644
index 0535d52..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config.go
+++ /dev/null
@@ -1,295 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
-)
-
-type comparable interface {
- equals(other interface{}) bool
-}
-
-// ATNConfig is a tuple: (ATN state, predicted alt, syntactic, semantic
-// context). The syntactic context is a graph-structured stack node whose
-// path(s) to the root is the rule invocation(s) chain used to arrive at the
-// state. The semantic context is the tree of semantic predicates encountered
-// before reaching an ATN state.
-type ATNConfig interface {
- comparable
-
- hash() int
-
- GetState() ATNState
- GetAlt() int
- GetSemanticContext() SemanticContext
-
- GetContext() PredictionContext
- SetContext(PredictionContext)
-
- GetReachesIntoOuterContext() int
- SetReachesIntoOuterContext(int)
-
- String() string
-
- getPrecedenceFilterSuppressed() bool
- setPrecedenceFilterSuppressed(bool)
-}
-
-type BaseATNConfig struct {
- precedenceFilterSuppressed bool
- state ATNState
- alt int
- context PredictionContext
- semanticContext SemanticContext
- reachesIntoOuterContext int
-}
-
-func NewBaseATNConfig7(old *BaseATNConfig) *BaseATNConfig { // TODO: Dup
- return &BaseATNConfig{
- state: old.state,
- alt: old.alt,
- context: old.context,
- semanticContext: old.semanticContext,
- reachesIntoOuterContext: old.reachesIntoOuterContext,
- }
-}
-
-func NewBaseATNConfig6(state ATNState, alt int, context PredictionContext) *BaseATNConfig {
- return NewBaseATNConfig5(state, alt, context, SemanticContextNone)
-}
-
-func NewBaseATNConfig5(state ATNState, alt int, context PredictionContext, semanticContext SemanticContext) *BaseATNConfig {
- if semanticContext == nil {
- panic("semanticContext cannot be nil") // TODO: Necessary?
- }
-
- return &BaseATNConfig{state: state, alt: alt, context: context, semanticContext: semanticContext}
-}
-
-func NewBaseATNConfig4(c ATNConfig, state ATNState) *BaseATNConfig {
- return NewBaseATNConfig(c, state, c.GetContext(), c.GetSemanticContext())
-}
-
-func NewBaseATNConfig3(c ATNConfig, state ATNState, semanticContext SemanticContext) *BaseATNConfig {
- return NewBaseATNConfig(c, state, c.GetContext(), semanticContext)
-}
-
-func NewBaseATNConfig2(c ATNConfig, semanticContext SemanticContext) *BaseATNConfig {
- return NewBaseATNConfig(c, c.GetState(), c.GetContext(), semanticContext)
-}
-
-func NewBaseATNConfig1(c ATNConfig, state ATNState, context PredictionContext) *BaseATNConfig {
- return NewBaseATNConfig(c, state, context, c.GetSemanticContext())
-}
-
-func NewBaseATNConfig(c ATNConfig, state ATNState, context PredictionContext, semanticContext SemanticContext) *BaseATNConfig {
- if semanticContext == nil {
- panic("semanticContext cannot be nil")
- }
-
- return &BaseATNConfig{
- state: state,
- alt: c.GetAlt(),
- context: context,
- semanticContext: semanticContext,
- reachesIntoOuterContext: c.GetReachesIntoOuterContext(),
- precedenceFilterSuppressed: c.getPrecedenceFilterSuppressed(),
- }
-}
-
-func (b *BaseATNConfig) getPrecedenceFilterSuppressed() bool {
- return b.precedenceFilterSuppressed
-}
-
-func (b *BaseATNConfig) setPrecedenceFilterSuppressed(v bool) {
- b.precedenceFilterSuppressed = v
-}
-
-func (b *BaseATNConfig) GetState() ATNState {
- return b.state
-}
-
-func (b *BaseATNConfig) GetAlt() int {
- return b.alt
-}
-
-func (b *BaseATNConfig) SetContext(v PredictionContext) {
- b.context = v
-}
-func (b *BaseATNConfig) GetContext() PredictionContext {
- return b.context
-}
-
-func (b *BaseATNConfig) GetSemanticContext() SemanticContext {
- return b.semanticContext
-}
-
-func (b *BaseATNConfig) GetReachesIntoOuterContext() int {
- return b.reachesIntoOuterContext
-}
-
-func (b *BaseATNConfig) SetReachesIntoOuterContext(v int) {
- b.reachesIntoOuterContext = v
-}
-
-// An ATN configuration is equal to another if both have the same state, they
-// predict the same alternative, and syntactic/semantic contexts are the same.
-func (b *BaseATNConfig) equals(o interface{}) bool {
- if b == o {
- return true
- }
-
- var other, ok = o.(*BaseATNConfig)
-
- if !ok {
- return false
- }
-
- var equal bool
-
- if b.context == nil {
- equal = other.context == nil
- } else {
- equal = b.context.equals(other.context)
- }
-
- var (
- nums = b.state.GetStateNumber() == other.state.GetStateNumber()
- alts = b.alt == other.alt
- cons = b.semanticContext.equals(other.semanticContext)
- sups = b.precedenceFilterSuppressed == other.precedenceFilterSuppressed
- )
-
- return nums && alts && cons && sups && equal
-}
-
-func (b *BaseATNConfig) hash() int {
- var c int
- if b.context != nil {
- c = b.context.hash()
- }
-
- h := murmurInit(7)
- h = murmurUpdate(h, b.state.GetStateNumber())
- h = murmurUpdate(h, b.alt)
- h = murmurUpdate(h, c)
- h = murmurUpdate(h, b.semanticContext.hash())
- return murmurFinish(h, 4)
-}
-
-func (b *BaseATNConfig) String() string {
- var s1, s2, s3 string
-
- if b.context != nil {
- s1 = ",[" + fmt.Sprint(b.context) + "]"
- }
-
- if b.semanticContext != SemanticContextNone {
- s2 = "," + fmt.Sprint(b.semanticContext)
- }
-
- if b.reachesIntoOuterContext > 0 {
- s3 = ",up=" + fmt.Sprint(b.reachesIntoOuterContext)
- }
-
- return fmt.Sprintf("(%v,%v%v%v%v)", b.state, b.alt, s1, s2, s3)
-}
-
-type LexerATNConfig struct {
- *BaseATNConfig
- lexerActionExecutor *LexerActionExecutor
- passedThroughNonGreedyDecision bool
-}
-
-func NewLexerATNConfig6(state ATNState, alt int, context PredictionContext) *LexerATNConfig {
- return &LexerATNConfig{BaseATNConfig: NewBaseATNConfig5(state, alt, context, SemanticContextNone)}
-}
-
-func NewLexerATNConfig5(state ATNState, alt int, context PredictionContext, lexerActionExecutor *LexerActionExecutor) *LexerATNConfig {
- return &LexerATNConfig{
- BaseATNConfig: NewBaseATNConfig5(state, alt, context, SemanticContextNone),
- lexerActionExecutor: lexerActionExecutor,
- }
-}
-
-func NewLexerATNConfig4(c *LexerATNConfig, state ATNState) *LexerATNConfig {
- return &LexerATNConfig{
- BaseATNConfig: NewBaseATNConfig(c, state, c.GetContext(), c.GetSemanticContext()),
- lexerActionExecutor: c.lexerActionExecutor,
- passedThroughNonGreedyDecision: checkNonGreedyDecision(c, state),
- }
-}
-
-func NewLexerATNConfig3(c *LexerATNConfig, state ATNState, lexerActionExecutor *LexerActionExecutor) *LexerATNConfig {
- return &LexerATNConfig{
- BaseATNConfig: NewBaseATNConfig(c, state, c.GetContext(), c.GetSemanticContext()),
- lexerActionExecutor: lexerActionExecutor,
- passedThroughNonGreedyDecision: checkNonGreedyDecision(c, state),
- }
-}
-
-func NewLexerATNConfig2(c *LexerATNConfig, state ATNState, context PredictionContext) *LexerATNConfig {
- return &LexerATNConfig{
- BaseATNConfig: NewBaseATNConfig(c, state, context, c.GetSemanticContext()),
- lexerActionExecutor: c.lexerActionExecutor,
- passedThroughNonGreedyDecision: checkNonGreedyDecision(c, state),
- }
-}
-
-func NewLexerATNConfig1(state ATNState, alt int, context PredictionContext) *LexerATNConfig {
- return &LexerATNConfig{BaseATNConfig: NewBaseATNConfig5(state, alt, context, SemanticContextNone)}
-}
-
-func (l *LexerATNConfig) hash() int {
- var f int
- if l.passedThroughNonGreedyDecision {
- f = 1
- } else {
- f = 0
- }
- h := murmurInit(7)
- h = murmurUpdate(h, l.state.hash())
- h = murmurUpdate(h, l.alt)
- h = murmurUpdate(h, l.context.hash())
- h = murmurUpdate(h, l.semanticContext.hash())
- h = murmurUpdate(h, f)
- h = murmurUpdate(h, l.lexerActionExecutor.hash())
- h = murmurFinish(h, 6)
- return h
-}
-
-func (l *LexerATNConfig) equals(other interface{}) bool {
- var othert, ok = other.(*LexerATNConfig)
-
- if l == other {
- return true
- } else if !ok {
- return false
- } else if l.passedThroughNonGreedyDecision != othert.passedThroughNonGreedyDecision {
- return false
- }
-
- var b bool
-
- if l.lexerActionExecutor != nil {
- b = !l.lexerActionExecutor.equals(othert.lexerActionExecutor)
- } else {
- b = othert.lexerActionExecutor != nil
- }
-
- if b {
- return false
- }
-
- return l.BaseATNConfig.equals(othert.BaseATNConfig)
-}
-
-
-func checkNonGreedyDecision(source *LexerATNConfig, target ATNState) bool {
- var ds, ok = target.(DecisionState)
-
- return source.passedThroughNonGreedyDecision || (ok && ds.getNonGreedy())
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config_set.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config_set.go
deleted file mode 100644
index d9f7475..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_config_set.go
+++ /dev/null
@@ -1,387 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import "fmt"
-
-type ATNConfigSet interface {
- hash() int
- Add(ATNConfig, *DoubleDict) bool
- AddAll([]ATNConfig) bool
-
- GetStates() *Set
- GetPredicates() []SemanticContext
- GetItems() []ATNConfig
-
- OptimizeConfigs(interpreter *BaseATNSimulator)
-
- Equals(other interface{}) bool
-
- Length() int
- IsEmpty() bool
- Contains(ATNConfig) bool
- ContainsFast(ATNConfig) bool
- Clear()
- String() string
-
- HasSemanticContext() bool
- SetHasSemanticContext(v bool)
-
- ReadOnly() bool
- SetReadOnly(bool)
-
- GetConflictingAlts() *BitSet
- SetConflictingAlts(*BitSet)
-
- FullContext() bool
-
- GetUniqueAlt() int
- SetUniqueAlt(int)
-
- GetDipsIntoOuterContext() bool
- SetDipsIntoOuterContext(bool)
-}
-
-// BaseATNConfigSet is a specialized set of ATNConfig that tracks information
-// about its elements and can combine similar configurations using a
-// graph-structured stack.
-type BaseATNConfigSet struct {
- cachedHash int
-
- // configLookup is used to determine whether two BaseATNConfigSets are equal. We
- // need all configurations with the same (s, i, _, semctx) to be equal. A key
- // effectively doubles the number of objects associated with ATNConfigs. All
- // keys are hashed by (s, i, _, pi), not including the context. Wiped out when
- // read-only because a set becomes a DFA state.
- configLookup *Set
-
- // configs is the added elements.
- configs []ATNConfig
-
- // TODO: These fields make me pretty uncomfortable, but it is nice to pack up
- // info together because it saves recomputation. Can we track conflicts as they
- // are added to save scanning configs later?
- conflictingAlts *BitSet
-
- // dipsIntoOuterContext is used by parsers and lexers. In a lexer, it indicates
- // we hit a pred while computing a closure operation. Do not make a DFA state
- // from the BaseATNConfigSet in this case. TODO: How is this used by parsers?
- dipsIntoOuterContext bool
-
- // fullCtx is whether it is part of a full context LL prediction. Used to
- // determine how to merge $. It is a wildcard with SLL, but not for an LL
- // context merge.
- fullCtx bool
-
- // Used in parser and lexer. In lexer, it indicates we hit a pred
- // while computing a closure operation. Don't make a DFA state from a.
- hasSemanticContext bool
-
- // readOnly is whether it is read-only. Do not
- // allow any code to manipulate the set if true because DFA states will point at
- // sets and those must not change. It not protect other fields; conflictingAlts
- // in particular, which is assigned after readOnly.
- readOnly bool
-
- // TODO: These fields make me pretty uncomfortable, but it is nice to pack up
- // info together because it saves recomputation. Can we track conflicts as they
- // are added to save scanning configs later?
- uniqueAlt int
-}
-
-func NewBaseATNConfigSet(fullCtx bool) *BaseATNConfigSet {
- return &BaseATNConfigSet{
- cachedHash: -1,
- configLookup: NewSet(nil, equalATNConfigs),
- fullCtx: fullCtx,
- }
-}
-
-// Add merges contexts with existing configs for (s, i, pi, _), where s is the
-// ATNConfig.state, i is the ATNConfig.alt, and pi is the
-// ATNConfig.semanticContext. We use (s,i,pi) as the key. Updates
-// dipsIntoOuterContext and hasSemanticContext when necessary.
-func (b *BaseATNConfigSet) Add(config ATNConfig, mergeCache *DoubleDict) bool {
- if b.readOnly {
- panic("set is read-only")
- }
-
- if config.GetSemanticContext() != SemanticContextNone {
- b.hasSemanticContext = true
- }
-
- if config.GetReachesIntoOuterContext() > 0 {
- b.dipsIntoOuterContext = true
- }
-
- existing := b.configLookup.add(config).(ATNConfig)
-
- if existing == config {
- b.cachedHash = -1
- b.configs = append(b.configs, config) // Track order here
-
- return true
- }
-
- // Merge a previous (s, i, pi, _) with it and save the result
- rootIsWildcard := !b.fullCtx
- merged := merge(existing.GetContext(), config.GetContext(), rootIsWildcard, mergeCache)
-
- // No need to check for existing.context because config.context is in the cache,
- // since the only way to create new graphs is the "call rule" and here. We cache
- // at both places.
- existing.SetReachesIntoOuterContext(intMax(existing.GetReachesIntoOuterContext(), config.GetReachesIntoOuterContext()))
-
- // Preserve the precedence filter suppression during the merge
- if config.getPrecedenceFilterSuppressed() {
- existing.setPrecedenceFilterSuppressed(true)
- }
-
- // Replace the context because there is no need to do alt mapping
- existing.SetContext(merged)
-
- return true
-}
-
-func (b *BaseATNConfigSet) GetStates() *Set {
- states := NewSet(nil, nil)
-
- for i := 0; i < len(b.configs); i++ {
- states.add(b.configs[i].GetState())
- }
-
- return states
-}
-
-func (b *BaseATNConfigSet) HasSemanticContext() bool {
- return b.hasSemanticContext
-}
-
-func (b *BaseATNConfigSet) SetHasSemanticContext(v bool) {
- b.hasSemanticContext = v
-}
-
-func (b *BaseATNConfigSet) GetPredicates() []SemanticContext {
- preds := make([]SemanticContext, 0)
-
- for i := 0; i < len(b.configs); i++ {
- c := b.configs[i].GetSemanticContext()
-
- if c != SemanticContextNone {
- preds = append(preds, c)
- }
- }
-
- return preds
-}
-
-func (b *BaseATNConfigSet) GetItems() []ATNConfig {
- return b.configs
-}
-
-func (b *BaseATNConfigSet) OptimizeConfigs(interpreter *BaseATNSimulator) {
- if b.readOnly {
- panic("set is read-only")
- }
-
- if b.configLookup.length() == 0 {
- return
- }
-
- for i := 0; i < len(b.configs); i++ {
- config := b.configs[i]
-
- config.SetContext(interpreter.getCachedContext(config.GetContext()))
- }
-}
-
-func (b *BaseATNConfigSet) AddAll(coll []ATNConfig) bool {
- for i := 0; i < len(coll); i++ {
- b.Add(coll[i], nil)
- }
-
- return false
-}
-
-func (b *BaseATNConfigSet) Equals(other interface{}) bool {
- if b == other {
- return true
- } else if _, ok := other.(*BaseATNConfigSet); !ok {
- return false
- }
-
- other2 := other.(*BaseATNConfigSet)
-
- return b.configs != nil &&
- // TODO: b.configs.equals(other2.configs) && // TODO: Is b necessary?
- b.fullCtx == other2.fullCtx &&
- b.uniqueAlt == other2.uniqueAlt &&
- b.conflictingAlts == other2.conflictingAlts &&
- b.hasSemanticContext == other2.hasSemanticContext &&
- b.dipsIntoOuterContext == other2.dipsIntoOuterContext
-}
-
-func (b *BaseATNConfigSet) hash() int {
- if b.readOnly {
- if b.cachedHash == -1 {
- b.cachedHash = b.hashCodeConfigs()
- }
-
- return b.cachedHash
- }
-
- return b.hashCodeConfigs()
-}
-
-func (b *BaseATNConfigSet) hashCodeConfigs() int {
- h := murmurInit(1)
- for _, c := range b.configs {
- if c != nil {
- h = murmurUpdate(h, c.hash())
- }
- }
- return murmurFinish(h, len(b.configs))
-}
-
-func (b *BaseATNConfigSet) Length() int {
- return len(b.configs)
-}
-
-func (b *BaseATNConfigSet) IsEmpty() bool {
- return len(b.configs) == 0
-}
-
-func (b *BaseATNConfigSet) Contains(item ATNConfig) bool {
- if b.configLookup == nil {
- panic("not implemented for read-only sets")
- }
-
- return b.configLookup.contains(item)
-}
-
-func (b *BaseATNConfigSet) ContainsFast(item ATNConfig) bool {
- if b.configLookup == nil {
- panic("not implemented for read-only sets")
- }
-
- return b.configLookup.contains(item) // TODO: containsFast is not implemented for Set
-}
-
-func (b *BaseATNConfigSet) Clear() {
- if b.readOnly {
- panic("set is read-only")
- }
-
- b.configs = make([]ATNConfig, 0)
- b.cachedHash = -1
- b.configLookup = NewSet(nil, equalATNConfigs)
-}
-
-func (b *BaseATNConfigSet) FullContext() bool {
- return b.fullCtx
-}
-
-func (b *BaseATNConfigSet) GetDipsIntoOuterContext() bool {
- return b.dipsIntoOuterContext
-}
-
-func (b *BaseATNConfigSet) SetDipsIntoOuterContext(v bool) {
- b.dipsIntoOuterContext = v
-}
-
-func (b *BaseATNConfigSet) GetUniqueAlt() int {
- return b.uniqueAlt
-}
-
-func (b *BaseATNConfigSet) SetUniqueAlt(v int) {
- b.uniqueAlt = v
-}
-
-func (b *BaseATNConfigSet) GetConflictingAlts() *BitSet {
- return b.conflictingAlts
-}
-
-func (b *BaseATNConfigSet) SetConflictingAlts(v *BitSet) {
- b.conflictingAlts = v
-}
-
-func (b *BaseATNConfigSet) ReadOnly() bool {
- return b.readOnly
-}
-
-func (b *BaseATNConfigSet) SetReadOnly(readOnly bool) {
- b.readOnly = readOnly
-
- if readOnly {
- b.configLookup = nil // Read only, so no need for the lookup cache
- }
-}
-
-func (b *BaseATNConfigSet) String() string {
- s := "["
-
- for i, c := range b.configs {
- s += c.String()
-
- if i != len(b.configs)-1 {
- s += ", "
- }
- }
-
- s += "]"
-
- if b.hasSemanticContext {
- s += ",hasSemanticContext=" + fmt.Sprint(b.hasSemanticContext)
- }
-
- if b.uniqueAlt != ATNInvalidAltNumber {
- s += ",uniqueAlt=" + fmt.Sprint(b.uniqueAlt)
- }
-
- if b.conflictingAlts != nil {
- s += ",conflictingAlts=" + b.conflictingAlts.String()
- }
-
- if b.dipsIntoOuterContext {
- s += ",dipsIntoOuterContext"
- }
-
- return s
-}
-
-type OrderedATNConfigSet struct {
- *BaseATNConfigSet
-}
-
-func NewOrderedATNConfigSet() *OrderedATNConfigSet {
- b := NewBaseATNConfigSet(false)
-
- b.configLookup = NewSet(nil, nil)
-
- return &OrderedATNConfigSet{BaseATNConfigSet: b}
-}
-
-func equalATNConfigs(a, b interface{}) bool {
- if a == nil || b == nil {
- return false
- }
-
- if a == b {
- return true
- }
-
- var ai, ok = a.(ATNConfig)
- var bi, ok1 = b.(ATNConfig)
-
- if !ok || !ok1 {
- return false
- }
-
- nums := ai.GetState().GetStateNumber() == bi.GetState().GetStateNumber()
- alts := ai.GetAlt() == bi.GetAlt()
- cons := ai.GetSemanticContext().equals(bi.GetSemanticContext())
-
- return nums && alts && cons
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserialization_options.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserialization_options.go
deleted file mode 100644
index 18b89ef..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserialization_options.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-var ATNDeserializationOptionsdefaultOptions = &ATNDeserializationOptions{true, false, false}
-
-type ATNDeserializationOptions struct {
- readOnly bool
- verifyATN bool
- generateRuleBypassTransitions bool
-}
-
-func NewATNDeserializationOptions(CopyFrom *ATNDeserializationOptions) *ATNDeserializationOptions {
- o := new(ATNDeserializationOptions)
-
- if CopyFrom != nil {
- o.readOnly = CopyFrom.readOnly
- o.verifyATN = CopyFrom.verifyATN
- o.generateRuleBypassTransitions = CopyFrom.generateRuleBypassTransitions
- }
-
- return o
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserializer.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserializer.go
deleted file mode 100644
index 884d39c..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_deserializer.go
+++ /dev/null
@@ -1,828 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "encoding/hex"
- "fmt"
- "strconv"
- "strings"
- "unicode/utf16"
-)
-
-// This is the earliest supported serialized UUID.
-// stick to serialized version for now, we don't need a UUID instance
-var BaseSerializedUUID = "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E"
-var AddedUnicodeSMP = "59627784-3BE5-417A-B9EB-8131A7286089"
-
-// This list contains all of the currently supported UUIDs, ordered by when
-// the feature first appeared in this branch.
-var SupportedUUIDs = []string{BaseSerializedUUID, AddedUnicodeSMP}
-
-var SerializedVersion = 3
-
-// This is the current serialized UUID.
-var SerializedUUID = AddedUnicodeSMP
-
-type LoopEndStateIntPair struct {
- item0 *LoopEndState
- item1 int
-}
-
-type BlockStartStateIntPair struct {
- item0 BlockStartState
- item1 int
-}
-
-type ATNDeserializer struct {
- deserializationOptions *ATNDeserializationOptions
- data []rune
- pos int
- uuid string
-}
-
-func NewATNDeserializer(options *ATNDeserializationOptions) *ATNDeserializer {
- if options == nil {
- options = ATNDeserializationOptionsdefaultOptions
- }
-
- return &ATNDeserializer{deserializationOptions: options}
-}
-
-func stringInSlice(a string, list []string) int {
- for i, b := range list {
- if b == a {
- return i
- }
- }
-
- return -1
-}
-
-// isFeatureSupported determines if a particular serialized representation of an
-// ATN supports a particular feature, identified by the UUID used for
-// serializing the ATN at the time the feature was first introduced. Feature is
-// the UUID marking the first time the feature was supported in the serialized
-// ATN. ActualUuid is the UUID of the actual serialized ATN which is currently
-// being deserialized. It returns true if actualUuid represents a serialized ATN
-// at or after the feature identified by feature was introduced, and otherwise
-// false.
-func (a *ATNDeserializer) isFeatureSupported(feature, actualUUID string) bool {
- idx1 := stringInSlice(feature, SupportedUUIDs)
-
- if idx1 < 0 {
- return false
- }
-
- idx2 := stringInSlice(actualUUID, SupportedUUIDs)
-
- return idx2 >= idx1
-}
-
-func (a *ATNDeserializer) DeserializeFromUInt16(data []uint16) *ATN {
- a.reset(utf16.Decode(data))
- a.checkVersion()
- a.checkUUID()
-
- atn := a.readATN()
-
- a.readStates(atn)
- a.readRules(atn)
- a.readModes(atn)
-
- sets := make([]*IntervalSet, 0)
-
- // First, deserialize sets with 16-bit arguments <= U+FFFF.
- sets = a.readSets(atn, sets, a.readInt)
- // Next, if the ATN was serialized with the Unicode SMP feature,
- // deserialize sets with 32-bit arguments <= U+10FFFF.
- if (a.isFeatureSupported(AddedUnicodeSMP, a.uuid)) {
- sets = a.readSets(atn, sets, a.readInt32)
- }
-
- a.readEdges(atn, sets)
- a.readDecisions(atn)
- a.readLexerActions(atn)
- a.markPrecedenceDecisions(atn)
- a.verifyATN(atn)
-
- if a.deserializationOptions.generateRuleBypassTransitions && atn.grammarType == ATNTypeParser {
- a.generateRuleBypassTransitions(atn)
- // Re-verify after modification
- a.verifyATN(atn)
- }
-
- return atn
-
-}
-
-func (a *ATNDeserializer) reset(data []rune) {
- temp := make([]rune, len(data))
-
- for i, c := range data {
- // Don't adjust the first value since that's the version number
- if i == 0 {
- temp[i] = c
- } else if c > 1 {
- temp[i] = c - 2
- } else {
- temp[i] = c + 65533
- }
- }
-
- a.data = temp
- a.pos = 0
-}
-
-func (a *ATNDeserializer) checkVersion() {
- version := a.readInt()
-
- if version != SerializedVersion {
- panic("Could not deserialize ATN with version " + strconv.Itoa(version) + " (expected " + strconv.Itoa(SerializedVersion) + ").")
- }
-}
-
-func (a *ATNDeserializer) checkUUID() {
- uuid := a.readUUID()
-
- if stringInSlice(uuid, SupportedUUIDs) < 0 {
- panic("Could not deserialize ATN with UUID: " + uuid + " (expected " + SerializedUUID + " or a legacy UUID).")
- }
-
- a.uuid = uuid
-}
-
-func (a *ATNDeserializer) readATN() *ATN {
- grammarType := a.readInt()
- maxTokenType := a.readInt()
-
- return NewATN(grammarType, maxTokenType)
-}
-
-func (a *ATNDeserializer) readStates(atn *ATN) {
- loopBackStateNumbers := make([]LoopEndStateIntPair, 0)
- endStateNumbers := make([]BlockStartStateIntPair, 0)
-
- nstates := a.readInt()
-
- for i := 0; i < nstates; i++ {
- stype := a.readInt()
-
- // Ignore bad types of states
- if stype == ATNStateInvalidType {
- atn.addState(nil)
-
- continue
- }
-
- ruleIndex := a.readInt()
-
- if ruleIndex == 0xFFFF {
- ruleIndex = -1
- }
-
- s := a.stateFactory(stype, ruleIndex)
-
- if stype == ATNStateLoopEnd {
- loopBackStateNumber := a.readInt()
-
- loopBackStateNumbers = append(loopBackStateNumbers, LoopEndStateIntPair{s.(*LoopEndState), loopBackStateNumber})
- } else if s2, ok := s.(BlockStartState); ok {
- endStateNumber := a.readInt()
-
- endStateNumbers = append(endStateNumbers, BlockStartStateIntPair{s2, endStateNumber})
- }
-
- atn.addState(s)
- }
-
- // Delay the assignment of loop back and end states until we know all the state
- // instances have been initialized
- for j := 0; j < len(loopBackStateNumbers); j++ {
- pair := loopBackStateNumbers[j]
-
- pair.item0.loopBackState = atn.states[pair.item1]
- }
-
- for j := 0; j < len(endStateNumbers); j++ {
- pair := endStateNumbers[j]
-
- pair.item0.setEndState(atn.states[pair.item1].(*BlockEndState))
- }
-
- numNonGreedyStates := a.readInt()
-
- for j := 0; j < numNonGreedyStates; j++ {
- stateNumber := a.readInt()
-
- atn.states[stateNumber].(DecisionState).setNonGreedy(true)
- }
-
- numPrecedenceStates := a.readInt()
-
- for j := 0; j < numPrecedenceStates; j++ {
- stateNumber := a.readInt()
-
- atn.states[stateNumber].(*RuleStartState).isPrecedenceRule = true
- }
-}
-
-func (a *ATNDeserializer) readRules(atn *ATN) {
- nrules := a.readInt()
-
- if atn.grammarType == ATNTypeLexer {
- atn.ruleToTokenType = make([]int, nrules) // TODO: initIntArray(nrules, 0)
- }
-
- atn.ruleToStartState = make([]*RuleStartState, nrules) // TODO: initIntArray(nrules, 0)
-
- for i := 0; i < nrules; i++ {
- s := a.readInt()
- startState := atn.states[s].(*RuleStartState)
-
- atn.ruleToStartState[i] = startState
-
- if atn.grammarType == ATNTypeLexer {
- tokenType := a.readInt()
-
- if tokenType == 0xFFFF {
- tokenType = TokenEOF
- }
-
- atn.ruleToTokenType[i] = tokenType
- }
- }
-
- atn.ruleToStopState = make([]*RuleStopState, nrules) //initIntArray(nrules, 0)
-
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- if s2, ok := state.(*RuleStopState); ok {
- atn.ruleToStopState[s2.ruleIndex] = s2
- atn.ruleToStartState[s2.ruleIndex].stopState = s2
- }
- }
-}
-
-func (a *ATNDeserializer) readModes(atn *ATN) {
- nmodes := a.readInt()
-
- for i := 0; i < nmodes; i++ {
- s := a.readInt()
-
- atn.modeToStartState = append(atn.modeToStartState, atn.states[s].(*TokensStartState))
- }
-}
-
-func (a *ATNDeserializer) readSets(atn *ATN, sets []*IntervalSet, readUnicode func() int) []*IntervalSet {
- m := a.readInt()
-
- for i := 0; i < m; i++ {
- iset := NewIntervalSet()
-
- sets = append(sets, iset)
-
- n := a.readInt()
- containsEOF := a.readInt()
-
- if containsEOF != 0 {
- iset.addOne(-1)
- }
-
- for j := 0; j < n; j++ {
- i1 := readUnicode()
- i2 := readUnicode()
-
- iset.addRange(i1, i2)
- }
- }
-
- return sets
-}
-
-func (a *ATNDeserializer) readEdges(atn *ATN, sets []*IntervalSet) {
- nedges := a.readInt()
-
- for i := 0; i < nedges; i++ {
- var (
- src = a.readInt()
- trg = a.readInt()
- ttype = a.readInt()
- arg1 = a.readInt()
- arg2 = a.readInt()
- arg3 = a.readInt()
- trans = a.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets)
- srcState = atn.states[src]
- )
-
- srcState.AddTransition(trans, -1)
- }
-
- // Edges for rule stop states can be derived, so they are not serialized
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- for j := 0; j < len(state.GetTransitions()); j++ {
- var t, ok = state.GetTransitions()[j].(*RuleTransition)
-
- if !ok {
- continue
- }
-
- outermostPrecedenceReturn := -1
-
- if atn.ruleToStartState[t.getTarget().GetRuleIndex()].isPrecedenceRule {
- if t.precedence == 0 {
- outermostPrecedenceReturn = t.getTarget().GetRuleIndex()
- }
- }
-
- trans := NewEpsilonTransition(t.followState, outermostPrecedenceReturn)
-
- atn.ruleToStopState[t.getTarget().GetRuleIndex()].AddTransition(trans, -1)
- }
- }
-
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- if s2, ok := state.(*BaseBlockStartState); ok {
- // We need to know the end state to set its start state
- if s2.endState == nil {
- panic("IllegalState")
- }
-
- // Block end states can only be associated to a single block start state
- if s2.endState.startState != nil {
- panic("IllegalState")
- }
-
- s2.endState.startState = state
- }
-
- if s2, ok := state.(*PlusLoopbackState); ok {
- for j := 0; j < len(s2.GetTransitions()); j++ {
- target := s2.GetTransitions()[j].getTarget()
-
- if t2, ok := target.(*PlusBlockStartState); ok {
- t2.loopBackState = state
- }
- }
- } else if s2, ok := state.(*StarLoopbackState); ok {
- for j := 0; j < len(s2.GetTransitions()); j++ {
- target := s2.GetTransitions()[j].getTarget()
-
- if t2, ok := target.(*StarLoopEntryState); ok {
- t2.loopBackState = state
- }
- }
- }
- }
-}
-
-func (a *ATNDeserializer) readDecisions(atn *ATN) {
- ndecisions := a.readInt()
-
- for i := 0; i < ndecisions; i++ {
- s := a.readInt()
- decState := atn.states[s].(DecisionState)
-
- atn.DecisionToState = append(atn.DecisionToState, decState)
- decState.setDecision(i)
- }
-}
-
-func (a *ATNDeserializer) readLexerActions(atn *ATN) {
- if atn.grammarType == ATNTypeLexer {
- count := a.readInt()
-
- atn.lexerActions = make([]LexerAction, count) // initIntArray(count, nil)
-
- for i := 0; i < count; i++ {
- actionType := a.readInt()
- data1 := a.readInt()
-
- if data1 == 0xFFFF {
- data1 = -1
- }
-
- data2 := a.readInt()
-
- if data2 == 0xFFFF {
- data2 = -1
- }
-
- lexerAction := a.lexerActionFactory(actionType, data1, data2)
-
- atn.lexerActions[i] = lexerAction
- }
- }
-}
-
-func (a *ATNDeserializer) generateRuleBypassTransitions(atn *ATN) {
- count := len(atn.ruleToStartState)
-
- for i := 0; i < count; i++ {
- atn.ruleToTokenType[i] = atn.maxTokenType + i + 1
- }
-
- for i := 0; i < count; i++ {
- a.generateRuleBypassTransition(atn, i)
- }
-}
-
-func (a *ATNDeserializer) generateRuleBypassTransition(atn *ATN, idx int) {
- bypassStart := NewBasicBlockStartState()
-
- bypassStart.ruleIndex = idx
- atn.addState(bypassStart)
-
- bypassStop := NewBlockEndState()
-
- bypassStop.ruleIndex = idx
- atn.addState(bypassStop)
-
- bypassStart.endState = bypassStop
-
- atn.defineDecisionState(bypassStart.BaseDecisionState)
-
- bypassStop.startState = bypassStart
-
- var excludeTransition Transition
- var endState ATNState
-
- if atn.ruleToStartState[idx].isPrecedenceRule {
- // Wrap from the beginning of the rule to the StarLoopEntryState
- endState = nil
-
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- if a.stateIsEndStateFor(state, idx) != nil {
- endState = state
- excludeTransition = state.(*StarLoopEntryState).loopBackState.GetTransitions()[0]
-
- break
- }
- }
-
- if excludeTransition == nil {
- panic("Couldn't identify final state of the precedence rule prefix section.")
- }
- } else {
- endState = atn.ruleToStopState[idx]
- }
-
- // All non-excluded transitions that currently target end state need to target
- // blockEnd instead
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- for j := 0; j < len(state.GetTransitions()); j++ {
- transition := state.GetTransitions()[j]
-
- if transition == excludeTransition {
- continue
- }
-
- if transition.getTarget() == endState {
- transition.setTarget(bypassStop)
- }
- }
- }
-
- // All transitions leaving the rule start state need to leave blockStart instead
- ruleToStartState := atn.ruleToStartState[idx]
- count := len(ruleToStartState.GetTransitions())
-
- for count > 0 {
- bypassStart.AddTransition(ruleToStartState.GetTransitions()[count-1], -1)
- ruleToStartState.SetTransitions([]Transition{ruleToStartState.GetTransitions()[len(ruleToStartState.GetTransitions())-1]})
- }
-
- // Link the new states
- atn.ruleToStartState[idx].AddTransition(NewEpsilonTransition(bypassStart, -1), -1)
- bypassStop.AddTransition(NewEpsilonTransition(endState, -1), -1)
-
- MatchState := NewBasicState()
-
- atn.addState(MatchState)
- MatchState.AddTransition(NewAtomTransition(bypassStop, atn.ruleToTokenType[idx]), -1)
- bypassStart.AddTransition(NewEpsilonTransition(MatchState, -1), -1)
-}
-
-func (a *ATNDeserializer) stateIsEndStateFor(state ATNState, idx int) ATNState {
- if state.GetRuleIndex() != idx {
- return nil
- }
-
- if _, ok := state.(*StarLoopEntryState); !ok {
- return nil
- }
-
- maybeLoopEndState := state.GetTransitions()[len(state.GetTransitions())-1].getTarget()
-
- if _, ok := maybeLoopEndState.(*LoopEndState); !ok {
- return nil
- }
-
- var _, ok = maybeLoopEndState.GetTransitions()[0].getTarget().(*RuleStopState)
-
- if maybeLoopEndState.(*LoopEndState).epsilonOnlyTransitions && ok {
- return state
- }
-
- return nil
-}
-
-// markPrecedenceDecisions analyzes the StarLoopEntryState states in the
-// specified ATN to set the StarLoopEntryState.precedenceRuleDecision field to
-// the correct value.
-func (a *ATNDeserializer) markPrecedenceDecisions(atn *ATN) {
- for _, state := range atn.states {
- if _, ok := state.(*StarLoopEntryState); !ok {
- continue
- }
-
- // We analyze the ATN to determine if a ATN decision state is the
- // decision for the closure block that determines whether a
- // precedence rule should continue or complete.
- if atn.ruleToStartState[state.GetRuleIndex()].isPrecedenceRule {
- maybeLoopEndState := state.GetTransitions()[len(state.GetTransitions())-1].getTarget()
-
- if s3, ok := maybeLoopEndState.(*LoopEndState); ok {
- var _, ok2 = maybeLoopEndState.GetTransitions()[0].getTarget().(*RuleStopState)
-
- if s3.epsilonOnlyTransitions && ok2 {
- state.(*StarLoopEntryState).precedenceRuleDecision = true
- }
- }
- }
- }
-}
-
-func (a *ATNDeserializer) verifyATN(atn *ATN) {
- if !a.deserializationOptions.verifyATN {
- return
- }
-
- // Verify assumptions
- for i := 0; i < len(atn.states); i++ {
- state := atn.states[i]
-
- if state == nil {
- continue
- }
-
- a.checkCondition(state.GetEpsilonOnlyTransitions() || len(state.GetTransitions()) <= 1, "")
-
- switch s2 := state.(type) {
- case *PlusBlockStartState:
- a.checkCondition(s2.loopBackState != nil, "")
-
- case *StarLoopEntryState:
- a.checkCondition(s2.loopBackState != nil, "")
- a.checkCondition(len(s2.GetTransitions()) == 2, "")
-
- switch s2 := state.(type) {
- case *StarBlockStartState:
- var _, ok2 = s2.GetTransitions()[1].getTarget().(*LoopEndState)
-
- a.checkCondition(ok2, "")
- a.checkCondition(!s2.nonGreedy, "")
-
- case *LoopEndState:
- var s3, ok2 = s2.GetTransitions()[1].getTarget().(*StarBlockStartState)
-
- a.checkCondition(ok2, "")
- a.checkCondition(s3.nonGreedy, "")
-
- default:
- panic("IllegalState")
- }
-
- case *StarLoopbackState:
- a.checkCondition(len(state.GetTransitions()) == 1, "")
-
- var _, ok2 = state.GetTransitions()[0].getTarget().(*StarLoopEntryState)
-
- a.checkCondition(ok2, "")
-
- case *LoopEndState:
- a.checkCondition(s2.loopBackState != nil, "")
-
- case *RuleStartState:
- a.checkCondition(s2.stopState != nil, "")
-
- case *BaseBlockStartState:
- a.checkCondition(s2.endState != nil, "")
-
- case *BlockEndState:
- a.checkCondition(s2.startState != nil, "")
-
- case DecisionState:
- a.checkCondition(len(s2.GetTransitions()) <= 1 || s2.getDecision() >= 0, "")
-
- default:
- var _, ok = s2.(*RuleStopState)
-
- a.checkCondition(len(s2.GetTransitions()) <= 1 || ok, "")
- }
- }
-}
-
-func (a *ATNDeserializer) checkCondition(condition bool, message string) {
- if !condition {
- if message == "" {
- message = "IllegalState"
- }
-
- panic(message)
- }
-}
-
-func (a *ATNDeserializer) readInt() int {
- v := a.data[a.pos]
-
- a.pos++
-
- return int(v)
-}
-
-func (a *ATNDeserializer) readInt32() int {
- var low = a.readInt()
- var high = a.readInt()
- return low | (high << 16)
-}
-
-//TODO
-//func (a *ATNDeserializer) readLong() int64 {
-// panic("Not implemented")
-// var low = a.readInt32()
-// var high = a.readInt32()
-// return (low & 0x00000000FFFFFFFF) | (high << int32)
-//}
-
-func createByteToHex() []string {
- bth := make([]string, 256)
-
- for i := 0; i < 256; i++ {
- bth[i] = strings.ToUpper(hex.EncodeToString([]byte{byte(i)}))
- }
-
- return bth
-}
-
-var byteToHex = createByteToHex()
-
-func (a *ATNDeserializer) readUUID() string {
- bb := make([]int, 16)
-
- for i := 7; i >= 0; i-- {
- integer := a.readInt()
-
- bb[(2*i)+1] = integer & 0xFF
- bb[2*i] = (integer >> 8) & 0xFF
- }
-
- return byteToHex[bb[0]] + byteToHex[bb[1]] +
- byteToHex[bb[2]] + byteToHex[bb[3]] + "-" +
- byteToHex[bb[4]] + byteToHex[bb[5]] + "-" +
- byteToHex[bb[6]] + byteToHex[bb[7]] + "-" +
- byteToHex[bb[8]] + byteToHex[bb[9]] + "-" +
- byteToHex[bb[10]] + byteToHex[bb[11]] +
- byteToHex[bb[12]] + byteToHex[bb[13]] +
- byteToHex[bb[14]] + byteToHex[bb[15]]
-}
-
-func (a *ATNDeserializer) edgeFactory(atn *ATN, typeIndex, src, trg, arg1, arg2, arg3 int, sets []*IntervalSet) Transition {
- target := atn.states[trg]
-
- switch typeIndex {
- case TransitionEPSILON:
- return NewEpsilonTransition(target, -1)
-
- case TransitionRANGE:
- if arg3 != 0 {
- return NewRangeTransition(target, TokenEOF, arg2)
- }
-
- return NewRangeTransition(target, arg1, arg2)
-
- case TransitionRULE:
- return NewRuleTransition(atn.states[arg1], arg2, arg3, target)
-
- case TransitionPREDICATE:
- return NewPredicateTransition(target, arg1, arg2, arg3 != 0)
-
- case TransitionPRECEDENCE:
- return NewPrecedencePredicateTransition(target, arg1)
-
- case TransitionATOM:
- if arg3 != 0 {
- return NewAtomTransition(target, TokenEOF)
- }
-
- return NewAtomTransition(target, arg1)
-
- case TransitionACTION:
- return NewActionTransition(target, arg1, arg2, arg3 != 0)
-
- case TransitionSET:
- return NewSetTransition(target, sets[arg1])
-
- case TransitionNOTSET:
- return NewNotSetTransition(target, sets[arg1])
-
- case TransitionWILDCARD:
- return NewWildcardTransition(target)
- }
-
- panic("The specified transition type is not valid.")
-}
-
-func (a *ATNDeserializer) stateFactory(typeIndex, ruleIndex int) ATNState {
- var s ATNState
-
- switch typeIndex {
- case ATNStateInvalidType:
- return nil
-
- case ATNStateBasic:
- s = NewBasicState()
-
- case ATNStateRuleStart:
- s = NewRuleStartState()
-
- case ATNStateBlockStart:
- s = NewBasicBlockStartState()
-
- case ATNStatePlusBlockStart:
- s = NewPlusBlockStartState()
-
- case ATNStateStarBlockStart:
- s = NewStarBlockStartState()
-
- case ATNStateTokenStart:
- s = NewTokensStartState()
-
- case ATNStateRuleStop:
- s = NewRuleStopState()
-
- case ATNStateBlockEnd:
- s = NewBlockEndState()
-
- case ATNStateStarLoopBack:
- s = NewStarLoopbackState()
-
- case ATNStateStarLoopEntry:
- s = NewStarLoopEntryState()
-
- case ATNStatePlusLoopBack:
- s = NewPlusLoopbackState()
-
- case ATNStateLoopEnd:
- s = NewLoopEndState()
-
- default:
- panic(fmt.Sprintf("state type %d is invalid", typeIndex))
- }
-
- s.SetRuleIndex(ruleIndex)
-
- return s
-}
-
-func (a *ATNDeserializer) lexerActionFactory(typeIndex, data1, data2 int) LexerAction {
- switch typeIndex {
- case LexerActionTypeChannel:
- return NewLexerChannelAction(data1)
-
- case LexerActionTypeCustom:
- return NewLexerCustomAction(data1, data2)
-
- case LexerActionTypeMode:
- return NewLexerModeAction(data1)
-
- case LexerActionTypeMore:
- return LexerMoreActionINSTANCE
-
- case LexerActionTypePopMode:
- return LexerPopModeActionINSTANCE
-
- case LexerActionTypePushMode:
- return NewLexerPushModeAction(data1)
-
- case LexerActionTypeSkip:
- return LexerSkipActionINSTANCE
-
- case LexerActionTypeType:
- return NewLexerTypeAction(data1)
-
- default:
- panic(fmt.Sprintf("lexer action %d is invalid", typeIndex))
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_simulator.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_simulator.go
deleted file mode 100644
index d5454d6..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_simulator.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-var ATNSimulatorError = NewDFAState(0x7FFFFFFF, NewBaseATNConfigSet(false))
-
-type IATNSimulator interface {
- SharedContextCache() *PredictionContextCache
- ATN() *ATN
- DecisionToDFA() []*DFA
-}
-
-type BaseATNSimulator struct {
- atn *ATN
- sharedContextCache *PredictionContextCache
- decisionToDFA []*DFA
-}
-
-func NewBaseATNSimulator(atn *ATN, sharedContextCache *PredictionContextCache) *BaseATNSimulator {
- b := new(BaseATNSimulator)
-
- b.atn = atn
- b.sharedContextCache = sharedContextCache
-
- return b
-}
-
-func (b *BaseATNSimulator) getCachedContext(context PredictionContext) PredictionContext {
- if b.sharedContextCache == nil {
- return context
- }
-
- visited := make(map[PredictionContext]PredictionContext)
-
- return getCachedBasePredictionContext(context, b.sharedContextCache, visited)
-}
-
-func (b *BaseATNSimulator) SharedContextCache() *PredictionContextCache {
- return b.sharedContextCache
-}
-
-func (b *BaseATNSimulator) ATN() *ATN {
- return b.atn
-}
-
-func (b *BaseATNSimulator) DecisionToDFA() []*DFA {
- return b.decisionToDFA
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_state.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_state.go
deleted file mode 100644
index 563d5db..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_state.go
+++ /dev/null
@@ -1,386 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import "strconv"
-
-// Constants for serialization.
-const (
- ATNStateInvalidType = 0
- ATNStateBasic = 1
- ATNStateRuleStart = 2
- ATNStateBlockStart = 3
- ATNStatePlusBlockStart = 4
- ATNStateStarBlockStart = 5
- ATNStateTokenStart = 6
- ATNStateRuleStop = 7
- ATNStateBlockEnd = 8
- ATNStateStarLoopBack = 9
- ATNStateStarLoopEntry = 10
- ATNStatePlusLoopBack = 11
- ATNStateLoopEnd = 12
-
- ATNStateInvalidStateNumber = -1
-)
-
-var ATNStateInitialNumTransitions = 4
-
-type ATNState interface {
- GetEpsilonOnlyTransitions() bool
-
- GetRuleIndex() int
- SetRuleIndex(int)
-
- GetNextTokenWithinRule() *IntervalSet
- SetNextTokenWithinRule(*IntervalSet)
-
- GetATN() *ATN
- SetATN(*ATN)
-
- GetStateType() int
-
- GetStateNumber() int
- SetStateNumber(int)
-
- GetTransitions() []Transition
- SetTransitions([]Transition)
- AddTransition(Transition, int)
-
- String() string
- hash() int
-}
-
-type BaseATNState struct {
- // NextTokenWithinRule caches lookahead during parsing. Not used during construction.
- NextTokenWithinRule *IntervalSet
-
- // atn is the current ATN.
- atn *ATN
-
- epsilonOnlyTransitions bool
-
- // ruleIndex tracks the Rule index because there are no Rule objects at runtime.
- ruleIndex int
-
- stateNumber int
-
- stateType int
-
- // Track the transitions emanating from this ATN state.
- transitions []Transition
-}
-
-func NewBaseATNState() *BaseATNState {
- return &BaseATNState{stateNumber: ATNStateInvalidStateNumber, stateType: ATNStateInvalidType}
-}
-
-func (as *BaseATNState) GetRuleIndex() int {
- return as.ruleIndex
-}
-
-func (as *BaseATNState) SetRuleIndex(v int) {
- as.ruleIndex = v
-}
-func (as *BaseATNState) GetEpsilonOnlyTransitions() bool {
- return as.epsilonOnlyTransitions
-}
-
-func (as *BaseATNState) GetATN() *ATN {
- return as.atn
-}
-
-func (as *BaseATNState) SetATN(atn *ATN) {
- as.atn = atn
-}
-
-func (as *BaseATNState) GetTransitions() []Transition {
- return as.transitions
-}
-
-func (as *BaseATNState) SetTransitions(t []Transition) {
- as.transitions = t
-}
-
-func (as *BaseATNState) GetStateType() int {
- return as.stateType
-}
-
-func (as *BaseATNState) GetStateNumber() int {
- return as.stateNumber
-}
-
-func (as *BaseATNState) SetStateNumber(stateNumber int) {
- as.stateNumber = stateNumber
-}
-
-func (as *BaseATNState) GetNextTokenWithinRule() *IntervalSet {
- return as.NextTokenWithinRule
-}
-
-func (as *BaseATNState) SetNextTokenWithinRule(v *IntervalSet) {
- as.NextTokenWithinRule = v
-}
-
-func (as *BaseATNState) hash() int {
- return as.stateNumber
-}
-
-func (as *BaseATNState) String() string {
- return strconv.Itoa(as.stateNumber)
-}
-
-func (as *BaseATNState) equals(other interface{}) bool {
- if ot, ok := other.(ATNState); ok {
- return as.stateNumber == ot.GetStateNumber()
- }
-
- return false
-}
-
-func (as *BaseATNState) isNonGreedyExitState() bool {
- return false
-}
-
-func (as *BaseATNState) AddTransition(trans Transition, index int) {
- if len(as.transitions) == 0 {
- as.epsilonOnlyTransitions = trans.getIsEpsilon()
- } else if as.epsilonOnlyTransitions != trans.getIsEpsilon() {
- as.epsilonOnlyTransitions = false
- }
-
- if index == -1 {
- as.transitions = append(as.transitions, trans)
- } else {
- as.transitions = append(as.transitions[:index], append([]Transition{trans}, as.transitions[index:]...)...)
- // TODO: as.transitions.splice(index, 1, trans)
- }
-}
-
-type BasicState struct {
- *BaseATNState
-}
-
-func NewBasicState() *BasicState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateBasic
-
- return &BasicState{BaseATNState: b}
-}
-
-type DecisionState interface {
- ATNState
-
- getDecision() int
- setDecision(int)
-
- getNonGreedy() bool
- setNonGreedy(bool)
-}
-
-type BaseDecisionState struct {
- *BaseATNState
- decision int
- nonGreedy bool
-}
-
-func NewBaseDecisionState() *BaseDecisionState {
- return &BaseDecisionState{BaseATNState: NewBaseATNState(), decision: -1}
-}
-
-func (s *BaseDecisionState) getDecision() int {
- return s.decision
-}
-
-func (s *BaseDecisionState) setDecision(b int) {
- s.decision = b
-}
-
-func (s *BaseDecisionState) getNonGreedy() bool {
- return s.nonGreedy
-}
-
-func (s *BaseDecisionState) setNonGreedy(b bool) {
- s.nonGreedy = b
-}
-
-type BlockStartState interface {
- DecisionState
-
- getEndState() *BlockEndState
- setEndState(*BlockEndState)
-}
-
-// BaseBlockStartState is the start of a regular (...) block.
-type BaseBlockStartState struct {
- *BaseDecisionState
- endState *BlockEndState
-}
-
-func NewBlockStartState() *BaseBlockStartState {
- return &BaseBlockStartState{BaseDecisionState: NewBaseDecisionState()}
-}
-
-func (s *BaseBlockStartState) getEndState() *BlockEndState {
- return s.endState
-}
-
-func (s *BaseBlockStartState) setEndState(b *BlockEndState) {
- s.endState = b
-}
-
-type BasicBlockStartState struct {
- *BaseBlockStartState
-}
-
-func NewBasicBlockStartState() *BasicBlockStartState {
- b := NewBlockStartState()
-
- b.stateType = ATNStateBlockStart
-
- return &BasicBlockStartState{BaseBlockStartState: b}
-}
-
-// BlockEndState is a terminal node of a simple (a|b|c) block.
-type BlockEndState struct {
- *BaseATNState
- startState ATNState
-}
-
-func NewBlockEndState() *BlockEndState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateBlockEnd
-
- return &BlockEndState{BaseATNState: b}
-}
-
-// RuleStopState is the last node in the ATN for a rule, unless that rule is the
-// start symbol. In that case, there is one transition to EOF. Later, we might
-// encode references to all calls to this rule to compute FOLLOW sets for error
-// handling.
-type RuleStopState struct {
- *BaseATNState
-}
-
-func NewRuleStopState() *RuleStopState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateRuleStop
-
- return &RuleStopState{BaseATNState: b}
-}
-
-type RuleStartState struct {
- *BaseATNState
- stopState ATNState
- isPrecedenceRule bool
-}
-
-func NewRuleStartState() *RuleStartState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateRuleStart
-
- return &RuleStartState{BaseATNState: b}
-}
-
-// PlusLoopbackState is a decision state for A+ and (A|B)+. It has two
-// transitions: one to the loop back to start of the block, and one to exit.
-type PlusLoopbackState struct {
- *BaseDecisionState
-}
-
-func NewPlusLoopbackState() *PlusLoopbackState {
- b := NewBaseDecisionState()
-
- b.stateType = ATNStatePlusLoopBack
-
- return &PlusLoopbackState{BaseDecisionState: b}
-}
-
-// PlusBlockStartState is the start of a (A|B|...)+ loop. Technically it is a
-// decision state; we don't use it for code generation. Somebody might need it,
-// it is included for completeness. In reality, PlusLoopbackState is the real
-// decision-making node for A+.
-type PlusBlockStartState struct {
- *BaseBlockStartState
- loopBackState ATNState
-}
-
-func NewPlusBlockStartState() *PlusBlockStartState {
- b := NewBlockStartState()
-
- b.stateType = ATNStatePlusBlockStart
-
- return &PlusBlockStartState{BaseBlockStartState: b}
-}
-
-// StarBlockStartState is the block that begins a closure loop.
-type StarBlockStartState struct {
- *BaseBlockStartState
-}
-
-func NewStarBlockStartState() *StarBlockStartState {
- b := NewBlockStartState()
-
- b.stateType = ATNStateStarBlockStart
-
- return &StarBlockStartState{BaseBlockStartState: b}
-}
-
-type StarLoopbackState struct {
- *BaseATNState
-}
-
-func NewStarLoopbackState() *StarLoopbackState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateStarLoopBack
-
- return &StarLoopbackState{BaseATNState: b}
-}
-
-type StarLoopEntryState struct {
- *BaseDecisionState
- loopBackState ATNState
- precedenceRuleDecision bool
-}
-
-func NewStarLoopEntryState() *StarLoopEntryState {
- b := NewBaseDecisionState()
-
- b.stateType = ATNStateStarLoopEntry
-
- // False precedenceRuleDecision indicates whether s state can benefit from a precedence DFA during SLL decision making.
- return &StarLoopEntryState{BaseDecisionState: b}
-}
-
-// LoopEndState marks the end of a * or + loop.
-type LoopEndState struct {
- *BaseATNState
- loopBackState ATNState
-}
-
-func NewLoopEndState() *LoopEndState {
- b := NewBaseATNState()
-
- b.stateType = ATNStateLoopEnd
-
- return &LoopEndState{BaseATNState: b}
-}
-
-// TokensStartState is the Tokens rule start state linking to each lexer rule start state.
-type TokensStartState struct {
- *BaseDecisionState
-}
-
-func NewTokensStartState() *TokensStartState {
- b := NewBaseDecisionState()
-
- b.stateType = ATNStateTokenStart
-
- return &TokensStartState{BaseDecisionState: b}
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_type.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_type.go
deleted file mode 100644
index a7b4897..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/atn_type.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// Represent the type of recognizer an ATN applies to.
-const (
- ATNTypeLexer = 0
- ATNTypeParser = 1
-)
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/char_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/char_stream.go
deleted file mode 100644
index 70c1207..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/char_stream.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type CharStream interface {
- IntStream
- GetText(int, int) string
- GetTextFromTokens(start, end Token) string
- GetTextFromInterval(*Interval) string
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_factory.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_factory.go
deleted file mode 100644
index 330ff8f..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_factory.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// TokenFactory creates CommonToken objects.
-type TokenFactory interface {
- Create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token
-}
-
-// CommonTokenFactory is the default TokenFactory implementation.
-type CommonTokenFactory struct {
- // copyText indicates whether CommonToken.setText should be called after
- // constructing tokens to explicitly set the text. This is useful for cases
- // where the input stream might not be able to provide arbitrary substrings of
- // text from the input after the lexer creates a token (e.g. the
- // implementation of CharStream.GetText in UnbufferedCharStream panics an
- // UnsupportedOperationException). Explicitly setting the token text allows
- // Token.GetText to be called at any time regardless of the input stream
- // implementation.
- //
- // The default value is false to avoid the performance and memory overhead of
- // copying text for every token unless explicitly requested.
- copyText bool
-}
-
-func NewCommonTokenFactory(copyText bool) *CommonTokenFactory {
- return &CommonTokenFactory{copyText: copyText}
-}
-
-// CommonTokenFactoryDEFAULT is the default CommonTokenFactory. It does not
-// explicitly copy token text when constructing tokens.
-var CommonTokenFactoryDEFAULT = NewCommonTokenFactory(false)
-
-func (c *CommonTokenFactory) Create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token {
- t := NewCommonToken(source, ttype, channel, start, stop)
-
- t.line = line
- t.column = column
-
- if text != "" {
- t.SetText(text)
- } else if c.copyText && source.charStream != nil {
- t.SetText(source.charStream.GetTextFromInterval(NewInterval(start, stop)))
- }
-
- return t
-}
-
-func (c *CommonTokenFactory) createThin(ttype int, text string) Token {
- t := NewCommonToken(nil, ttype, TokenDefaultChannel, -1, -1)
- t.SetText(text)
-
- return t
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_stream.go
deleted file mode 100644
index c90e9b8..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/common_token_stream.go
+++ /dev/null
@@ -1,447 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "strconv"
-)
-
-// CommonTokenStream is an implementation of TokenStream that loads tokens from
-// a TokenSource on-demand and places the tokens in a buffer to provide access
-// to any previous token by index. This token stream ignores the value of
-// Token.getChannel. If your parser requires the token stream filter tokens to
-// only those on a particular channel, such as Token.DEFAULT_CHANNEL or
-// Token.HIDDEN_CHANNEL, use a filtering token stream such a CommonTokenStream.
-type CommonTokenStream struct {
- channel int
-
- // fetchedEOF indicates whether the Token.EOF token has been fetched from
- // tokenSource and added to tokens. This field improves performance for the
- // following cases:
- //
- // consume: The lookahead check in consume to preven consuming the EOF symbol is
- // optimized by checking the values of fetchedEOF and p instead of calling LA.
- //
- // fetch: The check to prevent adding multiple EOF symbols into tokens is
- // trivial with bt field.
- fetchedEOF bool
-
- // index indexs into tokens of the current token (next token to consume).
- // tokens[p] should be LT(1). It is set to -1 when the stream is first
- // constructed or when SetTokenSource is called, indicating that the first token
- // has not yet been fetched from the token source. For additional information,
- // see the documentation of IntStream for a description of initializing methods.
- index int
-
- // tokenSource is the TokenSource from which tokens for the bt stream are
- // fetched.
- tokenSource TokenSource
-
- // tokens is all tokens fetched from the token source. The list is considered a
- // complete view of the input once fetchedEOF is set to true.
- tokens []Token
-}
-
-func NewCommonTokenStream(lexer Lexer, channel int) *CommonTokenStream {
- return &CommonTokenStream{
- channel: channel,
- index: -1,
- tokenSource: lexer,
- tokens: make([]Token, 0),
- }
-}
-
-func (c *CommonTokenStream) GetAllTokens() []Token {
- return c.tokens
-}
-
-func (c *CommonTokenStream) Mark() int {
- return 0
-}
-
-func (c *CommonTokenStream) Release(marker int) {}
-
-func (c *CommonTokenStream) reset() {
- c.Seek(0)
-}
-
-func (c *CommonTokenStream) Seek(index int) {
- c.lazyInit()
- c.index = c.adjustSeekIndex(index)
-}
-
-func (c *CommonTokenStream) Get(index int) Token {
- c.lazyInit()
-
- return c.tokens[index]
-}
-
-func (c *CommonTokenStream) Consume() {
- SkipEOFCheck := false
-
- if c.index >= 0 {
- if c.fetchedEOF {
- // The last token in tokens is EOF. Skip the check if p indexes any fetched.
- // token except the last.
- SkipEOFCheck = c.index < len(c.tokens)-1
- } else {
- // No EOF token in tokens. Skip the check if p indexes a fetched token.
- SkipEOFCheck = c.index < len(c.tokens)
- }
- } else {
- // Not yet initialized
- SkipEOFCheck = false
- }
-
- if !SkipEOFCheck && c.LA(1) == TokenEOF {
- panic("cannot consume EOF")
- }
-
- if c.Sync(c.index + 1) {
- c.index = c.adjustSeekIndex(c.index + 1)
- }
-}
-
-// Sync makes sure index i in tokens has a token and returns true if a token is
-// located at index i and otherwise false.
-func (c *CommonTokenStream) Sync(i int) bool {
- n := i - len(c.tokens) + 1 // TODO: How many more elements do we need?
-
- if n > 0 {
- fetched := c.fetch(n)
- return fetched >= n
- }
-
- return true
-}
-
-// fetch adds n elements to buffer and returns the actual number of elements
-// added to the buffer.
-func (c *CommonTokenStream) fetch(n int) int {
- if c.fetchedEOF {
- return 0
- }
-
- for i := 0; i < n; i++ {
- t := c.tokenSource.NextToken()
-
- t.SetTokenIndex(len(c.tokens))
- c.tokens = append(c.tokens, t)
-
- if t.GetTokenType() == TokenEOF {
- c.fetchedEOF = true
-
- return i + 1
- }
- }
-
- return n
-}
-
-// GetTokens gets all tokens from start to stop inclusive.
-func (c *CommonTokenStream) GetTokens(start int, stop int, types *IntervalSet) []Token {
- if start < 0 || stop < 0 {
- return nil
- }
-
- c.lazyInit()
-
- subset := make([]Token, 0)
-
- if stop >= len(c.tokens) {
- stop = len(c.tokens) - 1
- }
-
- for i := start; i < stop; i++ {
- t := c.tokens[i]
-
- if t.GetTokenType() == TokenEOF {
- break
- }
-
- if types == nil || types.contains(t.GetTokenType()) {
- subset = append(subset, t)
- }
- }
-
- return subset
-}
-
-func (c *CommonTokenStream) LA(i int) int {
- return c.LT(i).GetTokenType()
-}
-
-func (c *CommonTokenStream) lazyInit() {
- if c.index == -1 {
- c.setup()
- }
-}
-
-func (c *CommonTokenStream) setup() {
- c.Sync(0)
- c.index = c.adjustSeekIndex(0)
-}
-
-func (c *CommonTokenStream) GetTokenSource() TokenSource {
- return c.tokenSource
-}
-
-// SetTokenSource resets the c token stream by setting its token source.
-func (c *CommonTokenStream) SetTokenSource(tokenSource TokenSource) {
- c.tokenSource = tokenSource
- c.tokens = make([]Token, 0)
- c.index = -1
-}
-
-// NextTokenOnChannel returns the index of the next token on channel given a
-// starting index. Returns i if tokens[i] is on channel. Returns -1 if there are
-// no tokens on channel between i and EOF.
-func (c *CommonTokenStream) NextTokenOnChannel(i, channel int) int {
- c.Sync(i)
-
- if i >= len(c.tokens) {
- return -1
- }
-
- token := c.tokens[i]
-
- for token.GetChannel() != c.channel {
- if token.GetTokenType() == TokenEOF {
- return -1
- }
-
- i++
- c.Sync(i)
- token = c.tokens[i]
- }
-
- return i
-}
-
-// previousTokenOnChannel returns the index of the previous token on channel
-// given a starting index. Returns i if tokens[i] is on channel. Returns -1 if
-// there are no tokens on channel between i and 0.
-func (c *CommonTokenStream) previousTokenOnChannel(i, channel int) int {
- for i >= 0 && c.tokens[i].GetChannel() != channel {
- i--
- }
-
- return i
-}
-
-// GetHiddenTokensToRight collects all tokens on a specified channel to the
-// right of the current token up until we see a token on DEFAULT_TOKEN_CHANNEL
-// or EOF. If channel is -1, it finds any non-default channel token.
-func (c *CommonTokenStream) GetHiddenTokensToRight(tokenIndex, channel int) []Token {
- c.lazyInit()
-
- if tokenIndex < 0 || tokenIndex >= len(c.tokens) {
- panic(strconv.Itoa(tokenIndex) + " not in 0.." + strconv.Itoa(len(c.tokens)-1))
- }
-
- nextOnChannel := c.NextTokenOnChannel(tokenIndex+1, LexerDefaultTokenChannel)
- from := tokenIndex + 1
-
- // If no onchannel to the right, then nextOnChannel == -1, so set to to last token
- var to int
-
- if nextOnChannel == -1 {
- to = len(c.tokens) - 1
- } else {
- to = nextOnChannel
- }
-
- return c.filterForChannel(from, to, channel)
-}
-
-// GetHiddenTokensToLeft collects all tokens on channel to the left of the
-// current token until we see a token on DEFAULT_TOKEN_CHANNEL. If channel is
-// -1, it finds any non default channel token.
-func (c *CommonTokenStream) GetHiddenTokensToLeft(tokenIndex, channel int) []Token {
- c.lazyInit()
-
- if tokenIndex < 0 || tokenIndex >= len(c.tokens) {
- panic(strconv.Itoa(tokenIndex) + " not in 0.." + strconv.Itoa(len(c.tokens)-1))
- }
-
- prevOnChannel := c.previousTokenOnChannel(tokenIndex-1, LexerDefaultTokenChannel)
-
- if prevOnChannel == tokenIndex-1 {
- return nil
- }
-
- // If there are none on channel to the left and prevOnChannel == -1 then from = 0
- from := prevOnChannel + 1
- to := tokenIndex - 1
-
- return c.filterForChannel(from, to, channel)
-}
-
-func (c *CommonTokenStream) filterForChannel(left, right, channel int) []Token {
- hidden := make([]Token, 0)
-
- for i := left; i < right+1; i++ {
- t := c.tokens[i]
-
- if channel == -1 {
- if t.GetChannel() != LexerDefaultTokenChannel {
- hidden = append(hidden, t)
- }
- } else if t.GetChannel() == channel {
- hidden = append(hidden, t)
- }
- }
-
- if len(hidden) == 0 {
- return nil
- }
-
- return hidden
-}
-
-func (c *CommonTokenStream) GetSourceName() string {
- return c.tokenSource.GetSourceName()
-}
-
-func (c *CommonTokenStream) Size() int {
- return len(c.tokens)
-}
-
-func (c *CommonTokenStream) Index() int {
- return c.index
-}
-
-func (c *CommonTokenStream) GetAllText() string {
- return c.GetTextFromInterval(nil)
-}
-
-func (c *CommonTokenStream) GetTextFromTokens(start, end Token) string {
- if start == nil || end == nil {
- return ""
- }
-
- return c.GetTextFromInterval(NewInterval(start.GetTokenIndex(), end.GetTokenIndex()))
-}
-
-func (c *CommonTokenStream) GetTextFromRuleContext(interval RuleContext) string {
- return c.GetTextFromInterval(interval.GetSourceInterval())
-}
-
-func (c *CommonTokenStream) GetTextFromInterval(interval *Interval) string {
- c.lazyInit()
- c.Fill()
-
- if interval == nil {
- interval = NewInterval(0, len(c.tokens)-1)
- }
-
- start := interval.Start
- stop := interval.Stop
-
- if start < 0 || stop < 0 {
- return ""
- }
-
- if stop >= len(c.tokens) {
- stop = len(c.tokens) - 1
- }
-
- s := ""
-
- for i := start; i < stop+1; i++ {
- t := c.tokens[i]
-
- if t.GetTokenType() == TokenEOF {
- break
- }
-
- s += t.GetText()
- }
-
- return s
-}
-
-// Fill gets all tokens from the lexer until EOF.
-func (c *CommonTokenStream) Fill() {
- c.lazyInit()
-
- for c.fetch(1000) == 1000 {
- continue
- }
-}
-
-func (c *CommonTokenStream) adjustSeekIndex(i int) int {
- return c.NextTokenOnChannel(i, c.channel)
-}
-
-func (c *CommonTokenStream) LB(k int) Token {
- if k == 0 || c.index-k < 0 {
- return nil
- }
-
- i := c.index
- n := 1
-
- // Find k good tokens looking backward
- for n <= k {
- // Skip off-channel tokens
- i = c.previousTokenOnChannel(i-1, c.channel)
- n++
- }
-
- if i < 0 {
- return nil
- }
-
- return c.tokens[i]
-}
-
-func (c *CommonTokenStream) LT(k int) Token {
- c.lazyInit()
-
- if k == 0 {
- return nil
- }
-
- if k < 0 {
- return c.LB(-k)
- }
-
- i := c.index
- n := 1 // We know tokens[n] is valid
-
- // Find k good tokens
- for n < k {
- // Skip off-channel tokens, but make sure to not look past EOF
- if c.Sync(i + 1) {
- i = c.NextTokenOnChannel(i+1, c.channel)
- }
-
- n++
- }
-
- return c.tokens[i]
-}
-
-// getNumberOfOnChannelTokens counts EOF once.
-func (c *CommonTokenStream) getNumberOfOnChannelTokens() int {
- var n int
-
- c.Fill()
-
- for i := 0; i < len(c.tokens); i++ {
- t := c.tokens[i]
-
- if t.GetChannel() == c.channel {
- n++
- }
-
- if t.GetTokenType() == TokenEOF {
- break
- }
- }
-
- return n
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa.go
deleted file mode 100644
index d6079aa..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa.go
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "sort"
- "sync"
-)
-
-type DFA struct {
- // atnStartState is the ATN state in which this was created
- atnStartState DecisionState
-
- decision int
-
- // states is all the DFA states. Use Map to get the old state back; Set can only
- // indicate whether it is there.
- states map[int]*DFAState
- statesMu sync.RWMutex
-
- s0 *DFAState
- s0Mu sync.RWMutex
-
- // precedenceDfa is the backing field for isPrecedenceDfa and setPrecedenceDfa.
- // True if the DFA is for a precedence decision and false otherwise.
- precedenceDfa bool
-}
-
-func NewDFA(atnStartState DecisionState, decision int) *DFA {
- return &DFA{
- atnStartState: atnStartState,
- decision: decision,
- states: make(map[int]*DFAState),
- }
-}
-
-// getPrecedenceStartState gets the start state for the current precedence and
-// returns the start state corresponding to the specified precedence if a start
-// state exists for the specified precedence and nil otherwise. d must be a
-// precedence DFA. See also isPrecedenceDfa.
-func (d *DFA) getPrecedenceStartState(precedence int) *DFAState {
- if !d.precedenceDfa {
- panic("only precedence DFAs may contain a precedence start state")
- }
-
- d.s0Mu.RLock()
- defer d.s0Mu.RUnlock()
-
- // s0.edges is never nil for a precedence DFA
- if precedence < 0 || precedence >= len(d.s0.edges) {
- return nil
- }
-
- return d.s0.edges[precedence]
-}
-
-// setPrecedenceStartState sets the start state for the current precedence. d
-// must be a precedence DFA. See also isPrecedenceDfa.
-func (d *DFA) setPrecedenceStartState(precedence int, startState *DFAState) {
- if !d.precedenceDfa {
- panic("only precedence DFAs may contain a precedence start state")
- }
-
- if precedence < 0 {
- return
- }
-
- d.s0Mu.Lock()
- defer d.s0Mu.Unlock()
-
- // Synchronization on s0 here is ok. When the DFA is turned into a
- // precedence DFA, s0 will be initialized once and not updated again. s0.edges
- // is never nil for a precedence DFA.
- if precedence >= len(d.s0.edges) {
- d.s0.edges = append(d.s0.edges, make([]*DFAState, precedence+1-len(d.s0.edges))...)
- }
-
- d.s0.edges[precedence] = startState
-}
-
-// setPrecedenceDfa sets whether d is a precedence DFA. If precedenceDfa differs
-// from the current DFA configuration, then d.states is cleared, the initial
-// state s0 is set to a new DFAState with an empty outgoing DFAState.edges to
-// store the start states for individual precedence values if precedenceDfa is
-// true or nil otherwise, and d.precedenceDfa is updated.
-func (d *DFA) setPrecedenceDfa(precedenceDfa bool) {
- if d.precedenceDfa != precedenceDfa {
- d.states = make(map[int]*DFAState)
-
- if precedenceDfa {
- precedenceState := NewDFAState(-1, NewBaseATNConfigSet(false))
-
- precedenceState.edges = make([]*DFAState, 0)
- precedenceState.isAcceptState = false
- precedenceState.requiresFullContext = false
- d.s0 = precedenceState
- } else {
- d.s0 = nil
- }
-
- d.precedenceDfa = precedenceDfa
- }
-}
-
-func (d *DFA) getS0() *DFAState {
- d.s0Mu.RLock()
- defer d.s0Mu.RUnlock()
- return d.s0
-}
-
-func (d *DFA) setS0(s *DFAState) {
- d.s0Mu.Lock()
- defer d.s0Mu.Unlock()
- d.s0 = s
-}
-
-func (d *DFA) getState(hash int) (*DFAState, bool) {
- d.statesMu.RLock()
- defer d.statesMu.RUnlock()
- s, ok := d.states[hash]
- return s, ok
-}
-
-func (d *DFA) setState(hash int, state *DFAState) {
- d.statesMu.Lock()
- defer d.statesMu.Unlock()
- d.states[hash] = state
-}
-
-func (d *DFA) numStates() int {
- d.statesMu.RLock()
- defer d.statesMu.RUnlock()
- return len(d.states)
-}
-
-type dfaStateList []*DFAState
-
-func (d dfaStateList) Len() int { return len(d) }
-func (d dfaStateList) Less(i, j int) bool { return d[i].stateNumber < d[j].stateNumber }
-func (d dfaStateList) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
-
-// sortedStates returns the states in d sorted by their state number.
-func (d *DFA) sortedStates() []*DFAState {
- vs := make([]*DFAState, 0, len(d.states))
-
- for _, v := range d.states {
- vs = append(vs, v)
- }
-
- sort.Sort(dfaStateList(vs))
-
- return vs
-}
-
-func (d *DFA) String(literalNames []string, symbolicNames []string) string {
- if d.s0 == nil {
- return ""
- }
-
- return NewDFASerializer(d, literalNames, symbolicNames).String()
-}
-
-func (d *DFA) ToLexerString() string {
- if d.s0 == nil {
- return ""
- }
-
- return NewLexerDFASerializer(d).String()
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_serializer.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_serializer.go
deleted file mode 100644
index 4c0f690..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_serializer.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
-)
-
-// DFASerializer is a DFA walker that knows how to dump them to serialized
-// strings.
-type DFASerializer struct {
- dfa *DFA
- literalNames []string
- symbolicNames []string
-}
-
-func NewDFASerializer(dfa *DFA, literalNames, symbolicNames []string) *DFASerializer {
- if literalNames == nil {
- literalNames = make([]string, 0)
- }
-
- if symbolicNames == nil {
- symbolicNames = make([]string, 0)
- }
-
- return &DFASerializer{
- dfa: dfa,
- literalNames: literalNames,
- symbolicNames: symbolicNames,
- }
-}
-
-func (d *DFASerializer) String() string {
- if d.dfa.s0 == nil {
- return ""
- }
-
- buf := ""
- states := d.dfa.sortedStates()
-
- for _, s := range states {
- if s.edges != nil {
- n := len(s.edges)
-
- for j := 0; j < n; j++ {
- t := s.edges[j]
-
- if t != nil && t.stateNumber != 0x7FFFFFFF {
- buf += d.GetStateString(s)
- buf += "-"
- buf += d.getEdgeLabel(j)
- buf += "->"
- buf += d.GetStateString(t)
- buf += "\n"
- }
- }
- }
- }
-
- if len(buf) == 0 {
- return ""
- }
-
- return buf
-}
-
-func (d *DFASerializer) getEdgeLabel(i int) string {
- if i == 0 {
- return "EOF"
- } else if d.literalNames != nil && i-1 < len(d.literalNames) {
- return d.literalNames[i-1]
- } else if d.symbolicNames != nil && i-1 < len(d.symbolicNames) {
- return d.symbolicNames[i-1]
- }
-
- return strconv.Itoa(i - 1)
-}
-
-func (d *DFASerializer) GetStateString(s *DFAState) string {
- var a, b string
-
- if s.isAcceptState {
- a = ":"
- }
-
- if s.requiresFullContext {
- b = "^"
- }
-
- baseStateStr := a + "s" + strconv.Itoa(s.stateNumber) + b
-
- if s.isAcceptState {
- if s.predicates != nil {
- return baseStateStr + "=>" + fmt.Sprint(s.predicates)
- }
-
- return baseStateStr + "=>" + fmt.Sprint(s.prediction)
- }
-
- return baseStateStr
-}
-
-type LexerDFASerializer struct {
- *DFASerializer
-}
-
-func NewLexerDFASerializer(dfa *DFA) *LexerDFASerializer {
- return &LexerDFASerializer{DFASerializer: NewDFASerializer(dfa, nil, nil)}
-}
-
-func (l *LexerDFASerializer) getEdgeLabel(i int) string {
- return "'" + string(i) + "'"
-}
-
-func (l *LexerDFASerializer) String() string {
- if l.dfa.s0 == nil {
- return ""
- }
-
- buf := ""
- states := l.dfa.sortedStates()
-
- for i := 0; i < len(states); i++ {
- s := states[i]
-
- if s.edges != nil {
- n := len(s.edges)
-
- for j := 0; j < n; j++ {
- t := s.edges[j]
-
- if t != nil && t.stateNumber != 0x7FFFFFFF {
- buf += l.GetStateString(s)
- buf += "-"
- buf += l.getEdgeLabel(j)
- buf += "->"
- buf += l.GetStateString(t)
- buf += "\n"
- }
- }
- }
- }
-
- if len(buf) == 0 {
- return ""
- }
-
- return buf
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_state.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_state.go
deleted file mode 100644
index 38e918a..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/dfa_state.go
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
-)
-
-// PredPrediction maps a predicate to a predicted alternative.
-type PredPrediction struct {
- alt int
- pred SemanticContext
-}
-
-func NewPredPrediction(pred SemanticContext, alt int) *PredPrediction {
- return &PredPrediction{alt: alt, pred: pred}
-}
-
-func (p *PredPrediction) String() string {
- return "(" + fmt.Sprint(p.pred) + ", " + fmt.Sprint(p.alt) + ")"
-}
-
-// DFAState represents a set of possible ATN configurations. As Aho, Sethi,
-// Ullman p. 117 says: "The DFA uses its state to keep track of all possible
-// states the ATN can be in after reading each input symbol. That is to say,
-// after reading input a1a2..an, the DFA is in a state that represents the
-// subset T of the states of the ATN that are reachable from the ATN's start
-// state along some path labeled a1a2..an." In conventional NFA-to-DFA
-// conversion, therefore, the subset T would be a bitset representing the set of
-// states the ATN could be in. We need to track the alt predicted by each state
-// as well, however. More importantly, we need to maintain a stack of states,
-// tracking the closure operations as they jump from rule to rule, emulating
-// rule invocations (method calls). I have to add a stack to simulate the proper
-// lookahead sequences for the underlying LL grammar from which the ATN was
-// derived.
-//
-// I use a set of ATNConfig objects, not simple states. An ATNConfig is both a
-// state (ala normal conversion) and a RuleContext describing the chain of rules
-// (if any) followed to arrive at that state.
-//
-// A DFAState may have multiple references to a particular state, but with
-// different ATN contexts (with same or different alts) meaning that state was
-// reached via a different set of rule invocations.
-type DFAState struct {
- stateNumber int
- configs ATNConfigSet
-
- // edges elements point to the target of the symbol. Shift up by 1 so (-1)
- // Token.EOF maps to the first element.
- edges []*DFAState
-
- isAcceptState bool
-
- // prediction is the ttype we match or alt we predict if the state is accept.
- // Set to ATN.INVALID_ALT_NUMBER when predicates != nil or
- // requiresFullContext.
- prediction int
-
- lexerActionExecutor *LexerActionExecutor
-
- // requiresFullContext indicates it was created during an SLL prediction that
- // discovered a conflict between the configurations in the state. Future
- // ParserATNSimulator.execATN invocations immediately jump doing
- // full context prediction if true.
- requiresFullContext bool
-
- // predicates is the predicates associated with the ATN configurations of the
- // DFA state during SLL parsing. When we have predicates, requiresFullContext
- // is false, since full context prediction evaluates predicates on-the-fly. If
- // d is
- // not nil, then prediction is ATN.INVALID_ALT_NUMBER.
- //
- // We only use these for non-requiresFullContext but conflicting states. That
- // means we know from the context (it's $ or we don't dip into outer context)
- // that it's an ambiguity not a conflict.
- //
- // This list is computed by
- // ParserATNSimulator.predicateDFAState.
- predicates []*PredPrediction
-}
-
-func NewDFAState(stateNumber int, configs ATNConfigSet) *DFAState {
- if configs == nil {
- configs = NewBaseATNConfigSet(false)
- }
-
- return &DFAState{configs: configs, stateNumber: stateNumber}
-}
-
-// GetAltSet gets the set of all alts mentioned by all ATN configurations in d.
-func (d *DFAState) GetAltSet() *Set {
- alts := NewSet(nil, nil)
-
- if d.configs != nil {
- for _, c := range d.configs.GetItems() {
- alts.add(c.GetAlt())
- }
- }
-
- if alts.length() == 0 {
- return nil
- }
-
- return alts
-}
-
-func (d *DFAState) setPrediction(v int) {
- d.prediction = v
-}
-
-// equals returns whether d equals other. Two DFAStates are equal if their ATN
-// configuration sets are the same. This method is used to see if a state
-// already exists.
-//
-// Because the number of alternatives and number of ATN configurations are
-// finite, there is a finite number of DFA states that can be processed. This is
-// necessary to show that the algorithm terminates.
-//
-// Cannot test the DFA state numbers here because in
-// ParserATNSimulator.addDFAState we need to know if any other state exists that
-// has d exact set of ATN configurations. The stateNumber is irrelevant.
-func (d *DFAState) equals(other interface{}) bool {
- if d == other {
- return true
- } else if _, ok := other.(*DFAState); !ok {
- return false
- }
-
- return d.configs.Equals(other.(*DFAState).configs)
-}
-
-func (d *DFAState) String() string {
- var s string
- if d.isAcceptState {
- if d.predicates != nil {
- s = "=>" + fmt.Sprint(d.predicates)
- } else {
- s = "=>" + fmt.Sprint(d.prediction)
- }
- }
-
- return fmt.Sprintf("%d:%s%s", fmt.Sprint(d.configs), s)
-}
-
-func (d *DFAState) hash() int {
- h := murmurInit(11)
-
- c := 1
- if d.isAcceptState {
- if d.predicates != nil {
- for _, p := range d.predicates {
- h = murmurUpdate(h, p.alt)
- h = murmurUpdate(h, p.pred.hash())
- c += 2
- }
- } else {
- h = murmurUpdate(h, d.prediction)
- c += 1
- }
- }
-
- h = murmurUpdate(h, d.configs.hash())
- return murmurFinish(h, c)
-}
\ No newline at end of file
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/diagnostic_error_listener.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/diagnostic_error_listener.go
deleted file mode 100644
index 1fec43d..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/diagnostic_error_listener.go
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "strconv"
-)
-
-//
-// This implementation of {@link ANTLRErrorListener} can be used to identify
-// certain potential correctness and performance problems in grammars. "reports"
-// are made by calling {@link Parser//NotifyErrorListeners} with the appropriate
-// message.
-//
-//
-// - Ambiguities: These are cases where more than one path through the
-// grammar can Match the input.
-// - Weak context sensitivity: These are cases where full-context
-// prediction resolved an SLL conflict to a unique alternative which equaled the
-// minimum alternative of the SLL conflict.
-// - Strong (forced) context sensitivity: These are cases where the
-// full-context prediction resolved an SLL conflict to a unique alternative,
-// and the minimum alternative of the SLL conflict was found to not be
-// a truly viable alternative. Two-stage parsing cannot be used for inputs where
-// d situation occurs.
-//
-
-type DiagnosticErrorListener struct {
- *DefaultErrorListener
-
- exactOnly bool
-}
-
-func NewDiagnosticErrorListener(exactOnly bool) *DiagnosticErrorListener {
-
- n := new(DiagnosticErrorListener)
-
- // whether all ambiguities or only exact ambiguities are Reported.
- n.exactOnly = exactOnly
- return n
-}
-
-func (d *DiagnosticErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
- if d.exactOnly && !exact {
- return
- }
- msg := "reportAmbiguity d=" +
- d.getDecisionDescription(recognizer, dfa) +
- ": ambigAlts=" +
- d.getConflictingAlts(ambigAlts, configs).String() +
- ", input='" +
- recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'"
- recognizer.NotifyErrorListeners(msg, nil, nil)
-}
-
-func (d *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
-
- msg := "reportAttemptingFullContext d=" +
- d.getDecisionDescription(recognizer, dfa) +
- ", input='" +
- recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'"
- recognizer.NotifyErrorListeners(msg, nil, nil)
-}
-
-func (d *DiagnosticErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
- msg := "reportContextSensitivity d=" +
- d.getDecisionDescription(recognizer, dfa) +
- ", input='" +
- recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'"
- recognizer.NotifyErrorListeners(msg, nil, nil)
-}
-
-func (d *DiagnosticErrorListener) getDecisionDescription(recognizer Parser, dfa *DFA) string {
- decision := dfa.decision
- ruleIndex := dfa.atnStartState.GetRuleIndex()
-
- ruleNames := recognizer.GetRuleNames()
- if ruleIndex < 0 || ruleIndex >= len(ruleNames) {
- return strconv.Itoa(decision)
- }
- ruleName := ruleNames[ruleIndex]
- if ruleName == "" {
- return strconv.Itoa(decision)
- }
- return strconv.Itoa(decision) + " (" + ruleName + ")"
-}
-
-//
-// Computes the set of conflicting or ambiguous alternatives from a
-// configuration set, if that information was not already provided by the
-// parser.
-//
-// @param ReportedAlts The set of conflicting or ambiguous alternatives, as
-// Reported by the parser.
-// @param configs The conflicting or ambiguous configuration set.
-// @return Returns {@code ReportedAlts} if it is not {@code nil}, otherwise
-// returns the set of alternatives represented in {@code configs}.
-//
-func (d *DiagnosticErrorListener) getConflictingAlts(ReportedAlts *BitSet, set ATNConfigSet) *BitSet {
- if ReportedAlts != nil {
- return ReportedAlts
- }
- result := NewBitSet()
- for _, c := range set.GetItems() {
- result.add(c.GetAlt())
- }
-
- return result
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_listener.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_listener.go
deleted file mode 100644
index 028e1a9..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_listener.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "os"
- "strconv"
-)
-
-// Provides an empty default implementation of {@link ANTLRErrorListener}. The
-// default implementation of each method does nothing, but can be overridden as
-// necessary.
-
-type ErrorListener interface {
- SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException)
- ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet)
- ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet)
- ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet)
-}
-
-type DefaultErrorListener struct {
-}
-
-func NewDefaultErrorListener() *DefaultErrorListener {
- return new(DefaultErrorListener)
-}
-
-func (d *DefaultErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) {
-}
-
-func (d *DefaultErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
-}
-
-func (d *DefaultErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
-}
-
-func (d *DefaultErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
-}
-
-type ConsoleErrorListener struct {
- *DefaultErrorListener
-}
-
-func NewConsoleErrorListener() *ConsoleErrorListener {
- return new(ConsoleErrorListener)
-}
-
-//
-// Provides a default instance of {@link ConsoleErrorListener}.
-//
-var ConsoleErrorListenerINSTANCE = NewConsoleErrorListener()
-
-//
-// {@inheritDoc}
-//
-//
-// This implementation prints messages to {@link System//err} containing the
-// values of {@code line}, {@code charPositionInLine}, and {@code msg} using
-// the following format.
-//
-//
-// line line:charPositionInLine msg
-//
-//
-func (c *ConsoleErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) {
- fmt.Fprintln(os.Stderr, "line "+strconv.Itoa(line)+":"+strconv.Itoa(column)+" "+msg)
-}
-
-type ProxyErrorListener struct {
- *DefaultErrorListener
- delegates []ErrorListener
-}
-
-func NewProxyErrorListener(delegates []ErrorListener) *ProxyErrorListener {
- if delegates == nil {
- panic("delegates is not provided")
- }
- l := new(ProxyErrorListener)
- l.delegates = delegates
- return l
-}
-
-func (p *ProxyErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) {
- for _, d := range p.delegates {
- d.SyntaxError(recognizer, offendingSymbol, line, column, msg, e)
- }
-}
-
-func (p *ProxyErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
- for _, d := range p.delegates {
- d.ReportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs)
- }
-}
-
-func (p *ProxyErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) {
- for _, d := range p.delegates {
- d.ReportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs)
- }
-}
-
-func (p *ProxyErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) {
- for _, d := range p.delegates {
- d.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_strategy.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_strategy.go
deleted file mode 100644
index 977a6e4..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/error_strategy.go
+++ /dev/null
@@ -1,758 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "reflect"
- "strconv"
- "strings"
-)
-
-type ErrorStrategy interface {
- reset(Parser)
- RecoverInline(Parser) Token
- Recover(Parser, RecognitionException)
- Sync(Parser)
- inErrorRecoveryMode(Parser) bool
- ReportError(Parser, RecognitionException)
- ReportMatch(Parser)
-}
-
-// This is the default implementation of {@link ANTLRErrorStrategy} used for
-// error Reporting and recovery in ANTLR parsers.
-//
-type DefaultErrorStrategy struct {
- errorRecoveryMode bool
- lastErrorIndex int
- lastErrorStates *IntervalSet
-}
-
-var _ ErrorStrategy = &DefaultErrorStrategy{}
-
-func NewDefaultErrorStrategy() *DefaultErrorStrategy {
-
- d := new(DefaultErrorStrategy)
-
- // Indicates whether the error strategy is currently "recovering from an
- // error". This is used to suppress Reporting multiple error messages while
- // attempting to recover from a detected syntax error.
- //
- // @see //inErrorRecoveryMode
- //
- d.errorRecoveryMode = false
-
- // The index into the input stream where the last error occurred.
- // This is used to prevent infinite loops where an error is found
- // but no token is consumed during recovery...another error is found,
- // ad nauseum. This is a failsafe mechanism to guarantee that at least
- // one token/tree node is consumed for two errors.
- //
- d.lastErrorIndex = -1
- d.lastErrorStates = nil
- return d
-}
-
-// The default implementation simply calls {@link //endErrorCondition} to
-// ensure that the handler is not in error recovery mode.
-func (d *DefaultErrorStrategy) reset(recognizer Parser) {
- d.endErrorCondition(recognizer)
-}
-
-//
-// This method is called to enter error recovery mode when a recognition
-// exception is Reported.
-//
-// @param recognizer the parser instance
-//
-func (d *DefaultErrorStrategy) beginErrorCondition(recognizer Parser) {
- d.errorRecoveryMode = true
-}
-
-func (d *DefaultErrorStrategy) inErrorRecoveryMode(recognizer Parser) bool {
- return d.errorRecoveryMode
-}
-
-//
-// This method is called to leave error recovery mode after recovering from
-// a recognition exception.
-//
-// @param recognizer
-//
-func (d *DefaultErrorStrategy) endErrorCondition(recognizer Parser) {
- d.errorRecoveryMode = false
- d.lastErrorStates = nil
- d.lastErrorIndex = -1
-}
-
-//
-// {@inheritDoc}
-//
-// The default implementation simply calls {@link //endErrorCondition}.
-//
-func (d *DefaultErrorStrategy) ReportMatch(recognizer Parser) {
- d.endErrorCondition(recognizer)
-}
-
-//
-// {@inheritDoc}
-//
-// The default implementation returns immediately if the handler is already
-// in error recovery mode. Otherwise, it calls {@link //beginErrorCondition}
-// and dispatches the Reporting task based on the runtime type of {@code e}
-// according to the following table.
-//
-//
-// - {@link NoViableAltException}: Dispatches the call to
-// {@link //ReportNoViableAlternative}
-// - {@link InputMisMatchException}: Dispatches the call to
-// {@link //ReportInputMisMatch}
-// - {@link FailedPredicateException}: Dispatches the call to
-// {@link //ReportFailedPredicate}
-// - All other types: calls {@link Parser//NotifyErrorListeners} to Report
-// the exception
-//
-//
-func (d *DefaultErrorStrategy) ReportError(recognizer Parser, e RecognitionException) {
- // if we've already Reported an error and have not Matched a token
- // yet successfully, don't Report any errors.
- if d.inErrorRecoveryMode(recognizer) {
- return // don't Report spurious errors
- }
- d.beginErrorCondition(recognizer)
-
- switch t := e.(type) {
- default:
- fmt.Println("unknown recognition error type: " + reflect.TypeOf(e).Name())
- // fmt.Println(e.stack)
- recognizer.NotifyErrorListeners(e.GetMessage(), e.GetOffendingToken(), e)
- case *NoViableAltException:
- d.ReportNoViableAlternative(recognizer, t)
- case *InputMisMatchException:
- d.ReportInputMisMatch(recognizer, t)
- case *FailedPredicateException:
- d.ReportFailedPredicate(recognizer, t)
- }
-}
-
-// {@inheritDoc}
-//
-// The default implementation reSynchronizes the parser by consuming tokens
-// until we find one in the reSynchronization set--loosely the set of tokens
-// that can follow the current rule.
-//
-func (d *DefaultErrorStrategy) Recover(recognizer Parser, e RecognitionException) {
-
- if d.lastErrorIndex == recognizer.GetInputStream().Index() &&
- d.lastErrorStates != nil && d.lastErrorStates.contains(recognizer.GetState()) {
- // uh oh, another error at same token index and previously-Visited
- // state in ATN must be a case where LT(1) is in the recovery
- // token set so nothing got consumed. Consume a single token
- // at least to prevent an infinite loop d is a failsafe.
- recognizer.Consume()
- }
- d.lastErrorIndex = recognizer.GetInputStream().Index()
- if d.lastErrorStates == nil {
- d.lastErrorStates = NewIntervalSet()
- }
- d.lastErrorStates.addOne(recognizer.GetState())
- followSet := d.getErrorRecoverySet(recognizer)
- d.consumeUntil(recognizer, followSet)
-}
-
-// The default implementation of {@link ANTLRErrorStrategy//Sync} makes sure
-// that the current lookahead symbol is consistent with what were expecting
-// at d point in the ATN. You can call d anytime but ANTLR only
-// generates code to check before subrules/loops and each iteration.
-//
-// Implements Jim Idle's magic Sync mechanism in closures and optional
-// subrules. E.g.,
-//
-//
-// a : Sync ( stuff Sync )*
-// Sync : {consume to what can follow Sync}
-//
-//
-// At the start of a sub rule upon error, {@link //Sync} performs single
-// token deletion, if possible. If it can't do that, it bails on the current
-// rule and uses the default error recovery, which consumes until the
-// reSynchronization set of the current rule.
-//
-// If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
-// with an empty alternative), then the expected set includes what follows
-// the subrule.
-//
-// During loop iteration, it consumes until it sees a token that can start a
-// sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
-// stay in the loop as long as possible.
-//
-// ORIGINS
-//
-// Previous versions of ANTLR did a poor job of their recovery within loops.
-// A single mismatch token or missing token would force the parser to bail
-// out of the entire rules surrounding the loop. So, for rule
-//
-//
-// classfunc : 'class' ID '{' member* '}'
-//
-//
-// input with an extra token between members would force the parser to
-// consume until it found the next class definition rather than the next
-// member definition of the current class.
-//
-// This functionality cost a little bit of effort because the parser has to
-// compare token set at the start of the loop and at each iteration. If for
-// some reason speed is suffering for you, you can turn off d
-// functionality by simply overriding d method as a blank { }.
-//
-func (d *DefaultErrorStrategy) Sync(recognizer Parser) {
- // If already recovering, don't try to Sync
- if d.inErrorRecoveryMode(recognizer) {
- return
- }
-
- s := recognizer.GetInterpreter().atn.states[recognizer.GetState()]
- la := recognizer.GetTokenStream().LA(1)
-
- // try cheaper subset first might get lucky. seems to shave a wee bit off
- nextTokens := recognizer.GetATN().NextTokens(s, nil)
- if nextTokens.contains(TokenEpsilon) || nextTokens.contains(la) {
- return
- }
-
- switch s.GetStateType() {
- case ATNStateBlockStart, ATNStateStarBlockStart, ATNStatePlusBlockStart, ATNStateStarLoopEntry:
- // Report error and recover if possible
- if d.SingleTokenDeletion(recognizer) != nil {
- return
- }
- panic(NewInputMisMatchException(recognizer))
- case ATNStatePlusLoopBack, ATNStateStarLoopBack:
- d.ReportUnwantedToken(recognizer)
- expecting := NewIntervalSet()
- expecting.addSet(recognizer.GetExpectedTokens())
- whatFollowsLoopIterationOrRule := expecting.addSet(d.getErrorRecoverySet(recognizer))
- d.consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
- default:
- // do nothing if we can't identify the exact kind of ATN state
- }
-}
-
-// This is called by {@link //ReportError} when the exception is a
-// {@link NoViableAltException}.
-//
-// @see //ReportError
-//
-// @param recognizer the parser instance
-// @param e the recognition exception
-//
-func (d *DefaultErrorStrategy) ReportNoViableAlternative(recognizer Parser, e *NoViableAltException) {
- tokens := recognizer.GetTokenStream()
- var input string
- if tokens != nil {
- if e.startToken.GetTokenType() == TokenEOF {
- input = ""
- } else {
- input = tokens.GetTextFromTokens(e.startToken, e.offendingToken)
- }
- } else {
- input = ""
- }
- msg := "no viable alternative at input " + d.escapeWSAndQuote(input)
- recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
-}
-
-//
-// This is called by {@link //ReportError} when the exception is an
-// {@link InputMisMatchException}.
-//
-// @see //ReportError
-//
-// @param recognizer the parser instance
-// @param e the recognition exception
-//
-func (this *DefaultErrorStrategy) ReportInputMisMatch(recognizer Parser, e *InputMisMatchException) {
- msg := "mismatched input " + this.GetTokenErrorDisplay(e.offendingToken) +
- " expecting " + e.getExpectedTokens().StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)
- recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
-}
-
-//
-// This is called by {@link //ReportError} when the exception is a
-// {@link FailedPredicateException}.
-//
-// @see //ReportError
-//
-// @param recognizer the parser instance
-// @param e the recognition exception
-//
-func (d *DefaultErrorStrategy) ReportFailedPredicate(recognizer Parser, e *FailedPredicateException) {
- ruleName := recognizer.GetRuleNames()[recognizer.GetParserRuleContext().GetRuleIndex()]
- msg := "rule " + ruleName + " " + e.message
- recognizer.NotifyErrorListeners(msg, e.offendingToken, e)
-}
-
-// This method is called to Report a syntax error which requires the removal
-// of a token from the input stream. At the time d method is called, the
-// erroneous symbol is current {@code LT(1)} symbol and has not yet been
-// removed from the input stream. When d method returns,
-// {@code recognizer} is in error recovery mode.
-//
-// This method is called when {@link //singleTokenDeletion} identifies
-// single-token deletion as a viable recovery strategy for a mismatched
-// input error.
-//
-// The default implementation simply returns if the handler is already in
-// error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
-// enter error recovery mode, followed by calling
-// {@link Parser//NotifyErrorListeners}.
-//
-// @param recognizer the parser instance
-//
-func (d *DefaultErrorStrategy) ReportUnwantedToken(recognizer Parser) {
- if d.inErrorRecoveryMode(recognizer) {
- return
- }
- d.beginErrorCondition(recognizer)
- t := recognizer.GetCurrentToken()
- tokenName := d.GetTokenErrorDisplay(t)
- expecting := d.GetExpectedTokens(recognizer)
- msg := "extraneous input " + tokenName + " expecting " +
- expecting.StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false)
- recognizer.NotifyErrorListeners(msg, t, nil)
-}
-
-// This method is called to Report a syntax error which requires the
-// insertion of a missing token into the input stream. At the time d
-// method is called, the missing token has not yet been inserted. When d
-// method returns, {@code recognizer} is in error recovery mode.
-//
-// This method is called when {@link //singleTokenInsertion} identifies
-// single-token insertion as a viable recovery strategy for a mismatched
-// input error.
-//
-// The default implementation simply returns if the handler is already in
-// error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
-// enter error recovery mode, followed by calling
-// {@link Parser//NotifyErrorListeners}.
-//
-// @param recognizer the parser instance
-//
-func (d *DefaultErrorStrategy) ReportMissingToken(recognizer Parser) {
- if d.inErrorRecoveryMode(recognizer) {
- return
- }
- d.beginErrorCondition(recognizer)
- t := recognizer.GetCurrentToken()
- expecting := d.GetExpectedTokens(recognizer)
- msg := "missing " + expecting.StringVerbose(recognizer.GetLiteralNames(), recognizer.GetSymbolicNames(), false) +
- " at " + d.GetTokenErrorDisplay(t)
- recognizer.NotifyErrorListeners(msg, t, nil)
-}
-
-// The default implementation attempts to recover from the mismatched input
-// by using single token insertion and deletion as described below. If the
-// recovery attempt fails, d method panics an
-// {@link InputMisMatchException}.
-//
-// EXTRA TOKEN (single token deletion)
-//
-// {@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
-// right token, however, then assume {@code LA(1)} is some extra spurious
-// token and delete it. Then consume and return the next token (which was
-// the {@code LA(2)} token) as the successful result of the Match operation.
-//
-// This recovery strategy is implemented by {@link
-// //singleTokenDeletion}.
-//
-// MISSING TOKEN (single token insertion)
-//
-// If current token (at {@code LA(1)}) is consistent with what could come
-// after the expected {@code LA(1)} token, then assume the token is missing
-// and use the parser's {@link TokenFactory} to create it on the fly. The
-// "insertion" is performed by returning the created token as the successful
-// result of the Match operation.
-//
-// This recovery strategy is implemented by {@link
-// //singleTokenInsertion}.
-//
-// EXAMPLE
-//
-// For example, Input {@code i=(3} is clearly missing the {@code ')'}. When
-// the parser returns from the nested call to {@code expr}, it will have
-// call chain:
-//
-//
-// stat &rarr expr &rarr atom
-//
-//
-// and it will be trying to Match the {@code ')'} at d point in the
-// derivation:
-//
-//
-// => ID '=' '(' INT ')' ('+' atom)* ''
-// ^
-//
-//
-// The attempt to Match {@code ')'} will fail when it sees {@code ''} and
-// call {@link //recoverInline}. To recover, it sees that {@code LA(1)==''}
-// is in the set of tokens that can follow the {@code ')'} token reference
-// in rule {@code atom}. It can assume that you forgot the {@code ')'}.
-//
-func (d *DefaultErrorStrategy) RecoverInline(recognizer Parser) Token {
- // SINGLE TOKEN DELETION
- MatchedSymbol := d.SingleTokenDeletion(recognizer)
- if MatchedSymbol != nil {
- // we have deleted the extra token.
- // now, move past ttype token as if all were ok
- recognizer.Consume()
- return MatchedSymbol
- }
- // SINGLE TOKEN INSERTION
- if d.SingleTokenInsertion(recognizer) {
- return d.GetMissingSymbol(recognizer)
- }
- // even that didn't work must panic the exception
- panic(NewInputMisMatchException(recognizer))
-}
-
-//
-// This method implements the single-token insertion inline error recovery
-// strategy. It is called by {@link //recoverInline} if the single-token
-// deletion strategy fails to recover from the mismatched input. If this
-// method returns {@code true}, {@code recognizer} will be in error recovery
-// mode.
-//
-// This method determines whether or not single-token insertion is viable by
-// checking if the {@code LA(1)} input symbol could be successfully Matched
-// if it were instead the {@code LA(2)} symbol. If d method returns
-// {@code true}, the caller is responsible for creating and inserting a
-// token with the correct type to produce d behavior.
-//
-// @param recognizer the parser instance
-// @return {@code true} if single-token insertion is a viable recovery
-// strategy for the current mismatched input, otherwise {@code false}
-//
-func (d *DefaultErrorStrategy) SingleTokenInsertion(recognizer Parser) bool {
- currentSymbolType := recognizer.GetTokenStream().LA(1)
- // if current token is consistent with what could come after current
- // ATN state, then we know we're missing a token error recovery
- // is free to conjure up and insert the missing token
- atn := recognizer.GetInterpreter().atn
- currentState := atn.states[recognizer.GetState()]
- next := currentState.GetTransitions()[0].getTarget()
- expectingAtLL2 := atn.NextTokens(next, recognizer.GetParserRuleContext())
- if expectingAtLL2.contains(currentSymbolType) {
- d.ReportMissingToken(recognizer)
- return true
- }
-
- return false
-}
-
-// This method implements the single-token deletion inline error recovery
-// strategy. It is called by {@link //recoverInline} to attempt to recover
-// from mismatched input. If this method returns nil, the parser and error
-// handler state will not have changed. If this method returns non-nil,
-// {@code recognizer} will not be in error recovery mode since the
-// returned token was a successful Match.
-//
-// If the single-token deletion is successful, d method calls
-// {@link //ReportUnwantedToken} to Report the error, followed by
-// {@link Parser//consume} to actually "delete" the extraneous token. Then,
-// before returning {@link //ReportMatch} is called to signal a successful
-// Match.
-//
-// @param recognizer the parser instance
-// @return the successfully Matched {@link Token} instance if single-token
-// deletion successfully recovers from the mismatched input, otherwise
-// {@code nil}
-//
-func (d *DefaultErrorStrategy) SingleTokenDeletion(recognizer Parser) Token {
- NextTokenType := recognizer.GetTokenStream().LA(2)
- expecting := d.GetExpectedTokens(recognizer)
- if expecting.contains(NextTokenType) {
- d.ReportUnwantedToken(recognizer)
- // print("recoverFromMisMatchedToken deleting " \
- // + str(recognizer.GetTokenStream().LT(1)) \
- // + " since " + str(recognizer.GetTokenStream().LT(2)) \
- // + " is what we want", file=sys.stderr)
- recognizer.Consume() // simply delete extra token
- // we want to return the token we're actually Matching
- MatchedSymbol := recognizer.GetCurrentToken()
- d.ReportMatch(recognizer) // we know current token is correct
- return MatchedSymbol
- }
-
- return nil
-}
-
-// Conjure up a missing token during error recovery.
-//
-// The recognizer attempts to recover from single missing
-// symbols. But, actions might refer to that missing symbol.
-// For example, x=ID {f($x)}. The action clearly assumes
-// that there has been an identifier Matched previously and that
-// $x points at that token. If that token is missing, but
-// the next token in the stream is what we want we assume that
-// d token is missing and we keep going. Because we
-// have to return some token to replace the missing token,
-// we have to conjure one up. This method gives the user control
-// over the tokens returned for missing tokens. Mostly,
-// you will want to create something special for identifier
-// tokens. For literals such as '{' and ',', the default
-// action in the parser or tree parser works. It simply creates
-// a CommonToken of the appropriate type. The text will be the token.
-// If you change what tokens must be created by the lexer,
-// override d method to create the appropriate tokens.
-//
-func (d *DefaultErrorStrategy) GetMissingSymbol(recognizer Parser) Token {
- currentSymbol := recognizer.GetCurrentToken()
- expecting := d.GetExpectedTokens(recognizer)
- expectedTokenType := expecting.first()
- var tokenText string
-
- if expectedTokenType == TokenEOF {
- tokenText = ""
- } else {
- ln := recognizer.GetLiteralNames()
- if expectedTokenType > 0 && expectedTokenType < len(ln) {
- tokenText = ""
- } else {
- tokenText = "" // TODO matches the JS impl
- }
- }
- current := currentSymbol
- lookback := recognizer.GetTokenStream().LT(-1)
- if current.GetTokenType() == TokenEOF && lookback != nil {
- current = lookback
- }
-
- tf := recognizer.GetTokenFactory()
-
- return tf.Create(current.GetSource(), expectedTokenType, tokenText, TokenDefaultChannel, -1, -1, current.GetLine(), current.GetColumn())
-}
-
-func (d *DefaultErrorStrategy) GetExpectedTokens(recognizer Parser) *IntervalSet {
- return recognizer.GetExpectedTokens()
-}
-
-// How should a token be displayed in an error message? The default
-// is to display just the text, but during development you might
-// want to have a lot of information spit out. Override in that case
-// to use t.String() (which, for CommonToken, dumps everything about
-// the token). This is better than forcing you to override a method in
-// your token objects because you don't have to go modify your lexer
-// so that it creates a NewJava type.
-//
-func (d *DefaultErrorStrategy) GetTokenErrorDisplay(t Token) string {
- if t == nil {
- return ""
- }
- s := t.GetText()
- if s == "" {
- if t.GetTokenType() == TokenEOF {
- s = ""
- } else {
- s = "<" + strconv.Itoa(t.GetTokenType()) + ">"
- }
- }
- return d.escapeWSAndQuote(s)
-}
-
-func (d *DefaultErrorStrategy) escapeWSAndQuote(s string) string {
- s = strings.Replace(s, "\t", "\\t", -1)
- s = strings.Replace(s, "\n", "\\n", -1)
- s = strings.Replace(s, "\r", "\\r", -1)
- return "'" + s + "'"
-}
-
-// Compute the error recovery set for the current rule. During
-// rule invocation, the parser pushes the set of tokens that can
-// follow that rule reference on the stack d amounts to
-// computing FIRST of what follows the rule reference in the
-// enclosing rule. See LinearApproximator.FIRST().
-// This local follow set only includes tokens
-// from within the rule i.e., the FIRST computation done by
-// ANTLR stops at the end of a rule.
-//
-// EXAMPLE
-//
-// When you find a "no viable alt exception", the input is not
-// consistent with any of the alternatives for rule r. The best
-// thing to do is to consume tokens until you see something that
-// can legally follow a call to r//or* any rule that called r.
-// You don't want the exact set of viable next tokens because the
-// input might just be missing a token--you might consume the
-// rest of the input looking for one of the missing tokens.
-//
-// Consider grammar:
-//
-// a : '[' b ']'
-// | '(' b ')'
-//
-// b : c '^' INT
-// c : ID
-// | INT
-//
-//
-// At each rule invocation, the set of tokens that could follow
-// that rule is pushed on a stack. Here are the various
-// context-sensitive follow sets:
-//
-// FOLLOW(b1_in_a) = FIRST(']') = ']'
-// FOLLOW(b2_in_a) = FIRST(')') = ')'
-// FOLLOW(c_in_b) = FIRST('^') = '^'
-//
-// Upon erroneous input "[]", the call chain is
-//
-// a -> b -> c
-//
-// and, hence, the follow context stack is:
-//
-// depth follow set start of rule execution
-// 0 a (from main())
-// 1 ']' b
-// 2 '^' c
-//
-// Notice that ')' is not included, because b would have to have
-// been called from a different context in rule a for ')' to be
-// included.
-//
-// For error recovery, we cannot consider FOLLOW(c)
-// (context-sensitive or otherwise). We need the combined set of
-// all context-sensitive FOLLOW sets--the set of all tokens that
-// could follow any reference in the call chain. We need to
-// reSync to one of those tokens. Note that FOLLOW(c)='^' and if
-// we reSync'd to that token, we'd consume until EOF. We need to
-// Sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
-// In this case, for input "[]", LA(1) is ']' and in the set, so we would
-// not consume anything. After printing an error, rule c would
-// return normally. Rule b would not find the required '^' though.
-// At this point, it gets a mismatched token error and panics an
-// exception (since LA(1) is not in the viable following token
-// set). The rule exception handler tries to recover, but finds
-// the same recovery set and doesn't consume anything. Rule b
-// exits normally returning to rule a. Now it finds the ']' (and
-// with the successful Match exits errorRecovery mode).
-//
-// So, you can see that the parser walks up the call chain looking
-// for the token that was a member of the recovery set.
-//
-// Errors are not generated in errorRecovery mode.
-//
-// ANTLR's error recovery mechanism is based upon original ideas:
-//
-// "Algorithms + Data Structures = Programs" by Niklaus Wirth
-//
-// and
-//
-// "A note on error recovery in recursive descent parsers":
-// http://portal.acm.org/citation.cfm?id=947902.947905
-//
-// Later, Josef Grosch had some good ideas:
-//
-// "Efficient and Comfortable Error Recovery in Recursive Descent
-// Parsers":
-// ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
-//
-// Like Grosch I implement context-sensitive FOLLOW sets that are combined
-// at run-time upon error to avoid overhead during parsing.
-//
-func (d *DefaultErrorStrategy) getErrorRecoverySet(recognizer Parser) *IntervalSet {
- atn := recognizer.GetInterpreter().atn
- ctx := recognizer.GetParserRuleContext()
- recoverSet := NewIntervalSet()
- for ctx != nil && ctx.GetInvokingState() >= 0 {
- // compute what follows who invoked us
- invokingState := atn.states[ctx.GetInvokingState()]
- rt := invokingState.GetTransitions()[0]
- follow := atn.NextTokens(rt.(*RuleTransition).followState, nil)
- recoverSet.addSet(follow)
- ctx = ctx.GetParent().(ParserRuleContext)
- }
- recoverSet.removeOne(TokenEpsilon)
- return recoverSet
-}
-
-// Consume tokens until one Matches the given token set.//
-func (d *DefaultErrorStrategy) consumeUntil(recognizer Parser, set *IntervalSet) {
- ttype := recognizer.GetTokenStream().LA(1)
- for ttype != TokenEOF && !set.contains(ttype) {
- recognizer.Consume()
- ttype = recognizer.GetTokenStream().LA(1)
- }
-}
-
-//
-// This implementation of {@link ANTLRErrorStrategy} responds to syntax errors
-// by immediately canceling the parse operation with a
-// {@link ParseCancellationException}. The implementation ensures that the
-// {@link ParserRuleContext//exception} field is set for all parse tree nodes
-// that were not completed prior to encountering the error.
-//
-//
-// This error strategy is useful in the following scenarios.
-//
-//
-// - Two-stage parsing: This error strategy allows the first
-// stage of two-stage parsing to immediately terminate if an error is
-// encountered, and immediately fall back to the second stage. In addition to
-// avoiding wasted work by attempting to recover from errors here, the empty
-// implementation of {@link BailErrorStrategy//Sync} improves the performance of
-// the first stage.
-// - Silent validation: When syntax errors are not being
-// Reported or logged, and the parse result is simply ignored if errors occur,
-// the {@link BailErrorStrategy} avoids wasting work on recovering from errors
-// when the result will be ignored either way.
-//
-//
-//
-// {@code myparser.setErrorHandler(NewBailErrorStrategy())}
-//
-// @see Parser//setErrorHandler(ANTLRErrorStrategy)
-
-type BailErrorStrategy struct {
- *DefaultErrorStrategy
-}
-
-var _ ErrorStrategy = &BailErrorStrategy{}
-
-func NewBailErrorStrategy() *BailErrorStrategy {
-
- b := new(BailErrorStrategy)
-
- b.DefaultErrorStrategy = NewDefaultErrorStrategy()
-
- return b
-}
-
-// Instead of recovering from exception {@code e}, re-panic it wrapped
-// in a {@link ParseCancellationException} so it is not caught by the
-// rule func catches. Use {@link Exception//getCause()} to get the
-// original {@link RecognitionException}.
-//
-func (b *BailErrorStrategy) Recover(recognizer Parser, e RecognitionException) {
- context := recognizer.GetParserRuleContext()
- for context != nil {
- context.SetException(e)
- context = context.GetParent().(ParserRuleContext)
- }
- panic(NewParseCancellationException()) // TODO we don't emit e properly
-}
-
-// Make sure we don't attempt to recover inline if the parser
-// successfully recovers, it won't panic an exception.
-//
-func (b *BailErrorStrategy) RecoverInline(recognizer Parser) Token {
- b.Recover(recognizer, NewInputMisMatchException(recognizer))
-
- return nil
-}
-
-// Make sure we don't attempt to recover from problems in subrules.//
-func (b *BailErrorStrategy) Sync(recognizer Parser) {
- // pass
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/errors.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/errors.go
deleted file mode 100644
index 2ef7492..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/errors.go
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
-// 3 kinds of errors: prediction errors, failed predicate errors, and
-// mismatched input errors. In each case, the parser knows where it is
-// in the input, where it is in the ATN, the rule invocation stack,
-// and what kind of problem occurred.
-
-type RecognitionException interface {
- GetOffendingToken() Token
- GetMessage() string
- GetInputStream() IntStream
-}
-
-type BaseRecognitionException struct {
- message string
- recognizer Recognizer
- offendingToken Token
- offendingState int
- ctx RuleContext
- input IntStream
-}
-
-func NewBaseRecognitionException(message string, recognizer Recognizer, input IntStream, ctx RuleContext) *BaseRecognitionException {
-
- // todo
- // Error.call(this)
- //
- // if (!!Error.captureStackTrace) {
- // Error.captureStackTrace(this, RecognitionException)
- // } else {
- // stack := NewError().stack
- // }
- // TODO may be able to use - "runtime" func Stack(buf []byte, all bool) int
-
- t := new(BaseRecognitionException)
-
- t.message = message
- t.recognizer = recognizer
- t.input = input
- t.ctx = ctx
- // The current {@link Token} when an error occurred. Since not all streams
- // support accessing symbols by index, we have to track the {@link Token}
- // instance itself.
- t.offendingToken = nil
- // Get the ATN state number the parser was in at the time the error
- // occurred. For {@link NoViableAltException} and
- // {@link LexerNoViableAltException} exceptions, this is the
- // {@link DecisionState} number. For others, it is the state whose outgoing
- // edge we couldn't Match.
- t.offendingState = -1
- if t.recognizer != nil {
- t.offendingState = t.recognizer.GetState()
- }
-
- return t
-}
-
-func (b *BaseRecognitionException) GetMessage() string {
- return b.message
-}
-
-func (b *BaseRecognitionException) GetOffendingToken() Token {
- return b.offendingToken
-}
-
-func (b *BaseRecognitionException) GetInputStream() IntStream {
- return b.input
-}
-
-// If the state number is not known, b method returns -1.
-
-//
-// Gets the set of input symbols which could potentially follow the
-// previously Matched symbol at the time b exception was panicn.
-//
-// If the set of expected tokens is not known and could not be computed,
-// b method returns {@code nil}.
-//
-// @return The set of token types that could potentially follow the current
-// state in the ATN, or {@code nil} if the information is not available.
-// /
-func (b *BaseRecognitionException) getExpectedTokens() *IntervalSet {
- if b.recognizer != nil {
- return b.recognizer.GetATN().getExpectedTokens(b.offendingState, b.ctx)
- }
-
- return nil
-}
-
-func (b *BaseRecognitionException) String() string {
- return b.message
-}
-
-type LexerNoViableAltException struct {
- *BaseRecognitionException
-
- startIndex int
- deadEndConfigs ATNConfigSet
-}
-
-func NewLexerNoViableAltException(lexer Lexer, input CharStream, startIndex int, deadEndConfigs ATNConfigSet) *LexerNoViableAltException {
-
- l := new(LexerNoViableAltException)
-
- l.BaseRecognitionException = NewBaseRecognitionException("", lexer, input, nil)
-
- l.startIndex = startIndex
- l.deadEndConfigs = deadEndConfigs
-
- return l
-}
-
-func (l *LexerNoViableAltException) String() string {
- symbol := ""
- if l.startIndex >= 0 && l.startIndex < l.input.Size() {
- symbol = l.input.(CharStream).GetTextFromInterval(NewInterval(l.startIndex, l.startIndex))
- }
- return "LexerNoViableAltException" + symbol
-}
-
-type NoViableAltException struct {
- *BaseRecognitionException
-
- startToken Token
- offendingToken Token
- ctx ParserRuleContext
- deadEndConfigs ATNConfigSet
-}
-
-// Indicates that the parser could not decide which of two or more paths
-// to take based upon the remaining input. It tracks the starting token
-// of the offending input and also knows where the parser was
-// in the various paths when the error. Reported by ReportNoViableAlternative()
-//
-func NewNoViableAltException(recognizer Parser, input TokenStream, startToken Token, offendingToken Token, deadEndConfigs ATNConfigSet, ctx ParserRuleContext) *NoViableAltException {
-
- if ctx == nil {
- ctx = recognizer.GetParserRuleContext()
- }
-
- if offendingToken == nil {
- offendingToken = recognizer.GetCurrentToken()
- }
-
- if startToken == nil {
- startToken = recognizer.GetCurrentToken()
- }
-
- if input == nil {
- input = recognizer.GetInputStream().(TokenStream)
- }
-
- n := new(NoViableAltException)
- n.BaseRecognitionException = NewBaseRecognitionException("", recognizer, input, ctx)
-
- // Which configurations did we try at input.Index() that couldn't Match
- // input.LT(1)?//
- n.deadEndConfigs = deadEndConfigs
- // The token object at the start index the input stream might
- // not be buffering tokens so get a reference to it. (At the
- // time the error occurred, of course the stream needs to keep a
- // buffer all of the tokens but later we might not have access to those.)
- n.startToken = startToken
- n.offendingToken = offendingToken
-
- return n
-}
-
-type InputMisMatchException struct {
- *BaseRecognitionException
-}
-
-// This signifies any kind of mismatched input exceptions such as
-// when the current input does not Match the expected token.
-//
-func NewInputMisMatchException(recognizer Parser) *InputMisMatchException {
-
- i := new(InputMisMatchException)
- i.BaseRecognitionException = NewBaseRecognitionException("", recognizer, recognizer.GetInputStream(), recognizer.GetParserRuleContext())
-
- i.offendingToken = recognizer.GetCurrentToken()
-
- return i
-
-}
-
-// A semantic predicate failed during validation. Validation of predicates
-// occurs when normally parsing the alternative just like Matching a token.
-// Disambiguating predicate evaluation occurs when we test a predicate during
-// prediction.
-
-type FailedPredicateException struct {
- *BaseRecognitionException
-
- ruleIndex int
- predicateIndex int
- predicate string
-}
-
-func NewFailedPredicateException(recognizer Parser, predicate string, message string) *FailedPredicateException {
-
- f := new(FailedPredicateException)
-
- f.BaseRecognitionException = NewBaseRecognitionException(f.formatMessage(predicate, message), recognizer, recognizer.GetInputStream(), recognizer.GetParserRuleContext())
-
- s := recognizer.GetInterpreter().atn.states[recognizer.GetState()]
- trans := s.GetTransitions()[0]
- if trans2, ok := trans.(*PredicateTransition); ok {
- f.ruleIndex = trans2.ruleIndex
- f.predicateIndex = trans2.predIndex
- } else {
- f.ruleIndex = 0
- f.predicateIndex = 0
- }
- f.predicate = predicate
- f.offendingToken = recognizer.GetCurrentToken()
-
- return f
-}
-
-func (f *FailedPredicateException) formatMessage(predicate, message string) string {
- if message != "" {
- return message
- }
-
- return "failed predicate: {" + predicate + "}?"
-}
-
-type ParseCancellationException struct {
-}
-
-func NewParseCancellationException() *ParseCancellationException {
- // Error.call(this)
- // Error.captureStackTrace(this, ParseCancellationException)
- return new(ParseCancellationException)
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/file_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/file_stream.go
deleted file mode 100644
index 842170c..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/file_stream.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "bytes"
- "io"
- "os"
-)
-
-// This is an InputStream that is loaded from a file all at once
-// when you construct the object.
-
-type FileStream struct {
- *InputStream
-
- filename string
-}
-
-func NewFileStream(fileName string) (*FileStream, error) {
-
- buf := bytes.NewBuffer(nil)
-
- f, err := os.Open(fileName)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- _, err = io.Copy(buf, f)
- if err != nil {
- return nil, err
- }
-
- fs := new(FileStream)
-
- fs.filename = fileName
- s := string(buf.Bytes())
-
- fs.InputStream = NewInputStream(s)
-
- return fs, nil
-
-}
-
-func (f *FileStream) GetSourceName() string {
- return f.filename
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/input_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/input_stream.go
deleted file mode 100644
index 5ff270f..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/input_stream.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type InputStream struct {
- name string
- index int
- data []rune
- size int
-}
-
-func NewInputStream(data string) *InputStream {
-
- is := new(InputStream)
-
- is.name = ""
- is.index = 0
- is.data = []rune(data)
- is.size = len(is.data) // number of runes
-
- return is
-}
-
-func (is *InputStream) reset() {
- is.index = 0
-}
-
-func (is *InputStream) Consume() {
- if is.index >= is.size {
- // assert is.LA(1) == TokenEOF
- panic("cannot consume EOF")
- }
- is.index++
-}
-
-func (is *InputStream) LA(offset int) int {
-
- if offset == 0 {
- return 0 // nil
- }
- if offset < 0 {
- offset++ // e.g., translate LA(-1) to use offset=0
- }
- pos := is.index + offset - 1
-
- if pos < 0 || pos >= is.size { // invalid
- return TokenEOF
- }
-
- return int(is.data[pos])
-}
-
-func (is *InputStream) LT(offset int) int {
- return is.LA(offset)
-}
-
-func (is *InputStream) Index() int {
- return is.index
-}
-
-func (is *InputStream) Size() int {
- return is.size
-}
-
-// mark/release do nothing we have entire buffer
-func (is *InputStream) Mark() int {
- return -1
-}
-
-func (is *InputStream) Release(marker int) {
-}
-
-func (is *InputStream) Seek(index int) {
- if index <= is.index {
- is.index = index // just jump don't update stream state (line,...)
- return
- }
- // seek forward
- is.index = intMin(index, is.size)
-}
-
-func (is *InputStream) GetText(start int, stop int) string {
- if stop >= is.size {
- stop = is.size - 1
- }
- if start >= is.size {
- return ""
- }
-
- return string(is.data[start : stop+1])
-}
-
-func (is *InputStream) GetTextFromTokens(start, stop Token) string {
- if start != nil && stop != nil {
- return is.GetTextFromInterval(NewInterval(start.GetTokenIndex(), stop.GetTokenIndex()))
- }
-
- return ""
-}
-
-func (is *InputStream) GetTextFromInterval(i *Interval) string {
- return is.GetText(i.Start, i.Stop)
-}
-
-func (*InputStream) GetSourceName() string {
- return "Obtained from string"
-}
-
-func (is *InputStream) String() string {
- return string(is.data)
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/int_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/int_stream.go
deleted file mode 100644
index 438e0ea..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/int_stream.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type IntStream interface {
- Consume()
- LA(int) int
- Mark() int
- Release(marker int)
- Index() int
- Seek(index int)
- Size() int
- GetSourceName() string
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/interval_set.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/interval_set.go
deleted file mode 100644
index 510d909..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/interval_set.go
+++ /dev/null
@@ -1,296 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "strconv"
- "strings"
-)
-
-type Interval struct {
- Start int
- Stop int
-}
-
-/* stop is not included! */
-func NewInterval(start, stop int) *Interval {
- i := new(Interval)
-
- i.Start = start
- i.Stop = stop
- return i
-}
-
-func (i *Interval) Contains(item int) bool {
- return item >= i.Start && item < i.Stop
-}
-
-func (i *Interval) String() string {
- if i.Start == i.Stop-1 {
- return strconv.Itoa(i.Start)
- }
-
- return strconv.Itoa(i.Start) + ".." + strconv.Itoa(i.Stop-1)
-}
-
-func (i *Interval) length() int {
- return i.Stop - i.Start
-}
-
-type IntervalSet struct {
- intervals []*Interval
- readOnly bool
-}
-
-func NewIntervalSet() *IntervalSet {
-
- i := new(IntervalSet)
-
- i.intervals = nil
- i.readOnly = false
-
- return i
-}
-
-func (i *IntervalSet) first() int {
- if len(i.intervals) == 0 {
- return TokenInvalidType
- }
-
- return i.intervals[0].Start
-}
-
-func (i *IntervalSet) addOne(v int) {
- i.addInterval(NewInterval(v, v+1))
-}
-
-func (i *IntervalSet) addRange(l, h int) {
- i.addInterval(NewInterval(l, h+1))
-}
-
-func (i *IntervalSet) addInterval(v *Interval) {
- if i.intervals == nil {
- i.intervals = make([]*Interval, 0)
- i.intervals = append(i.intervals, v)
- } else {
- // find insert pos
- for k, interval := range i.intervals {
- // distinct range -> insert
- if v.Stop < interval.Start {
- i.intervals = append(i.intervals[0:k], append([]*Interval{v}, i.intervals[k:]...)...)
- return
- } else if v.Stop == interval.Start {
- i.intervals[k].Start = v.Start
- return
- } else if v.Start <= interval.Stop {
- i.intervals[k] = NewInterval(intMin(interval.Start, v.Start), intMax(interval.Stop, v.Stop))
-
- // if not applying to end, merge potential overlaps
- if k < len(i.intervals)-1 {
- l := i.intervals[k]
- r := i.intervals[k+1]
- // if r contained in l
- if l.Stop >= r.Stop {
- i.intervals = append(i.intervals[0:k+1], i.intervals[k+2:]...)
- } else if l.Stop >= r.Start { // partial overlap
- i.intervals[k] = NewInterval(l.Start, r.Stop)
- i.intervals = append(i.intervals[0:k+1], i.intervals[k+2:]...)
- }
- }
- return
- }
- }
- // greater than any exiting
- i.intervals = append(i.intervals, v)
- }
-}
-
-func (i *IntervalSet) addSet(other *IntervalSet) *IntervalSet {
- if other.intervals != nil {
- for k := 0; k < len(other.intervals); k++ {
- i2 := other.intervals[k]
- i.addInterval(NewInterval(i2.Start, i2.Stop))
- }
- }
- return i
-}
-
-func (i *IntervalSet) complement(start int, stop int) *IntervalSet {
- result := NewIntervalSet()
- result.addInterval(NewInterval(start, stop+1))
- for j := 0; j < len(i.intervals); j++ {
- result.removeRange(i.intervals[j])
- }
- return result
-}
-
-func (i *IntervalSet) contains(item int) bool {
- if i.intervals == nil {
- return false
- }
- for k := 0; k < len(i.intervals); k++ {
- if i.intervals[k].Contains(item) {
- return true
- }
- }
- return false
-}
-
-func (i *IntervalSet) length() int {
- len := 0
-
- for _, v := range i.intervals {
- len += v.length()
- }
-
- return len
-}
-
-func (i *IntervalSet) removeRange(v *Interval) {
- if v.Start == v.Stop-1 {
- i.removeOne(v.Start)
- } else if i.intervals != nil {
- k := 0
- for n := 0; n < len(i.intervals); n++ {
- ni := i.intervals[k]
- // intervals are ordered
- if v.Stop <= ni.Start {
- return
- } else if v.Start > ni.Start && v.Stop < ni.Stop {
- i.intervals[k] = NewInterval(ni.Start, v.Start)
- x := NewInterval(v.Stop, ni.Stop)
- // i.intervals.splice(k, 0, x)
- i.intervals = append(i.intervals[0:k], append([]*Interval{x}, i.intervals[k:]...)...)
- return
- } else if v.Start <= ni.Start && v.Stop >= ni.Stop {
- // i.intervals.splice(k, 1)
- i.intervals = append(i.intervals[0:k], i.intervals[k+1:]...)
- k = k - 1 // need another pass
- } else if v.Start < ni.Stop {
- i.intervals[k] = NewInterval(ni.Start, v.Start)
- } else if v.Stop < ni.Stop {
- i.intervals[k] = NewInterval(v.Stop, ni.Stop)
- }
- k++
- }
- }
-}
-
-func (i *IntervalSet) removeOne(v int) {
- if i.intervals != nil {
- for k := 0; k < len(i.intervals); k++ {
- ki := i.intervals[k]
- // intervals i ordered
- if v < ki.Start {
- return
- } else if v == ki.Start && v == ki.Stop-1 {
- // i.intervals.splice(k, 1)
- i.intervals = append(i.intervals[0:k], i.intervals[k+1:]...)
- return
- } else if v == ki.Start {
- i.intervals[k] = NewInterval(ki.Start+1, ki.Stop)
- return
- } else if v == ki.Stop-1 {
- i.intervals[k] = NewInterval(ki.Start, ki.Stop-1)
- return
- } else if v < ki.Stop-1 {
- x := NewInterval(ki.Start, v)
- ki.Start = v + 1
- // i.intervals.splice(k, 0, x)
- i.intervals = append(i.intervals[0:k], append([]*Interval{x}, i.intervals[k:]...)...)
- return
- }
- }
- }
-}
-
-func (i *IntervalSet) String() string {
- return i.StringVerbose(nil, nil, false)
-}
-
-func (i *IntervalSet) StringVerbose(literalNames []string, symbolicNames []string, elemsAreChar bool) string {
-
- if i.intervals == nil {
- return "{}"
- } else if literalNames != nil || symbolicNames != nil {
- return i.toTokenString(literalNames, symbolicNames)
- } else if elemsAreChar {
- return i.toCharString()
- }
-
- return i.toIndexString()
-}
-
-func (i *IntervalSet) toCharString() string {
- names := make([]string, len(i.intervals))
-
- for j := 0; j < len(i.intervals); j++ {
- v := i.intervals[j]
- if v.Stop == v.Start+1 {
- if v.Start == TokenEOF {
- names = append(names, "")
- } else {
- names = append(names, ("'" + string(v.Start) + "'"))
- }
- } else {
- names = append(names, "'"+string(v.Start)+"'..'"+string(v.Stop-1)+"'")
- }
- }
- if len(names) > 1 {
- return "{" + strings.Join(names, ", ") + "}"
- }
-
- return names[0]
-}
-
-func (i *IntervalSet) toIndexString() string {
-
- names := make([]string, 0)
- for j := 0; j < len(i.intervals); j++ {
- v := i.intervals[j]
- if v.Stop == v.Start+1 {
- if v.Start == TokenEOF {
- names = append(names, "")
- } else {
- names = append(names, strconv.Itoa(v.Start))
- }
- } else {
- names = append(names, strconv.Itoa(v.Start)+".."+strconv.Itoa(v.Stop-1))
- }
- }
- if len(names) > 1 {
- return "{" + strings.Join(names, ", ") + "}"
- }
-
- return names[0]
-}
-
-func (i *IntervalSet) toTokenString(literalNames []string, symbolicNames []string) string {
- names := make([]string, 0)
- for _, v := range i.intervals {
- for j := v.Start; j < v.Stop; j++ {
- names = append(names, i.elementName(literalNames, symbolicNames, j))
- }
- }
- if len(names) > 1 {
- return "{" + strings.Join(names, ", ") + "}"
- }
-
- return names[0]
-}
-
-func (i *IntervalSet) elementName(literalNames []string, symbolicNames []string, a int) string {
- if a == TokenEOF {
- return ""
- } else if a == TokenEpsilon {
- return ""
- } else {
- if a < len(literalNames) && literalNames[a] != "" {
- return literalNames[a]
- }
-
- return symbolicNames[a]
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer.go
deleted file mode 100644
index 02deaf9..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer.go
+++ /dev/null
@@ -1,417 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
-)
-
-// A lexer is recognizer that draws input symbols from a character stream.
-// lexer grammars result in a subclass of this object. A Lexer object
-// uses simplified Match() and error recovery mechanisms in the interest
-// of speed.
-///
-
-type Lexer interface {
- TokenSource
- Recognizer
-
- Emit() Token
-
- SetChannel(int)
- PushMode(int)
- PopMode() int
- SetType(int)
- SetMode(int)
-}
-
-type BaseLexer struct {
- *BaseRecognizer
-
- Interpreter ILexerATNSimulator
- TokenStartCharIndex int
- TokenStartLine int
- TokenStartColumn int
- ActionType int
- Virt Lexer // The most derived lexer implementation. Allows virtual method calls.
-
- input CharStream
- factory TokenFactory
- tokenFactorySourcePair *TokenSourceCharStreamPair
- token Token
- hitEOF bool
- channel int
- thetype int
- modeStack IntStack
- mode int
- text string
-}
-
-func NewBaseLexer(input CharStream) *BaseLexer {
-
- lexer := new(BaseLexer)
-
- lexer.BaseRecognizer = NewBaseRecognizer()
-
- lexer.input = input
- lexer.factory = CommonTokenFactoryDEFAULT
- lexer.tokenFactorySourcePair = &TokenSourceCharStreamPair{lexer, input}
-
- lexer.Virt = lexer
-
- lexer.Interpreter = nil // child classes must populate it
-
- // The goal of all lexer rules/methods is to create a token object.
- // l is an instance variable as multiple rules may collaborate to
- // create a single token. NextToken will return l object after
- // Matching lexer rule(s). If you subclass to allow multiple token
- // emissions, then set l to the last token to be Matched or
- // something nonnil so that the auto token emit mechanism will not
- // emit another token.
- lexer.token = nil
-
- // What character index in the stream did the current token start at?
- // Needed, for example, to get the text for current token. Set at
- // the start of NextToken.
- lexer.TokenStartCharIndex = -1
-
- // The line on which the first character of the token resides///
- lexer.TokenStartLine = -1
-
- // The character position of first character within the line///
- lexer.TokenStartColumn = -1
-
- // Once we see EOF on char stream, next token will be EOF.
- // If you have DONE : EOF then you see DONE EOF.
- lexer.hitEOF = false
-
- // The channel number for the current token///
- lexer.channel = TokenDefaultChannel
-
- // The token type for the current token///
- lexer.thetype = TokenInvalidType
-
- lexer.modeStack = make([]int, 0)
- lexer.mode = LexerDefaultMode
-
- // You can set the text for the current token to override what is in
- // the input char buffer. Use setText() or can set l instance var.
- // /
- lexer.text = ""
-
- return lexer
-}
-
-const (
- LexerDefaultMode = 0
- LexerMore = -2
- LexerSkip = -3
-)
-
-const (
- LexerDefaultTokenChannel = TokenDefaultChannel
- LexerHidden = TokenHiddenChannel
- LexerMinCharValue = 0x0000
- LexerMaxCharValue = 0x10FFFF
-)
-
-func (b *BaseLexer) reset() {
- // wack Lexer state variables
- if b.input != nil {
- b.input.Seek(0) // rewind the input
- }
- b.token = nil
- b.thetype = TokenInvalidType
- b.channel = TokenDefaultChannel
- b.TokenStartCharIndex = -1
- b.TokenStartColumn = -1
- b.TokenStartLine = -1
- b.text = ""
-
- b.hitEOF = false
- b.mode = LexerDefaultMode
- b.modeStack = make([]int, 0)
-
- b.Interpreter.reset()
-}
-
-func (b *BaseLexer) GetInterpreter() ILexerATNSimulator {
- return b.Interpreter
-}
-
-func (b *BaseLexer) GetInputStream() CharStream {
- return b.input
-}
-
-func (b *BaseLexer) GetSourceName() string {
- return b.GrammarFileName
-}
-
-func (b *BaseLexer) SetChannel(v int) {
- b.channel = v
-}
-
-func (b *BaseLexer) GetTokenFactory() TokenFactory {
- return b.factory
-}
-
-func (b *BaseLexer) setTokenFactory(f TokenFactory) {
- b.factory = f
-}
-
-func (b *BaseLexer) safeMatch() (ret int) {
- defer func() {
- if e := recover(); e != nil {
- if re, ok := e.(RecognitionException); ok {
- b.notifyListeners(re) // Report error
- b.Recover(re)
- ret = LexerSkip // default
- }
- }
- }()
-
- return b.Interpreter.Match(b.input, b.mode)
-}
-
-// Return a token from l source i.e., Match a token on the char stream.
-func (b *BaseLexer) NextToken() Token {
- if b.input == nil {
- panic("NextToken requires a non-nil input stream.")
- }
-
- tokenStartMarker := b.input.Mark()
-
- // previously in finally block
- defer func() {
- // make sure we release marker after Match or
- // unbuffered char stream will keep buffering
- b.input.Release(tokenStartMarker)
- }()
-
- for {
- if b.hitEOF {
- b.EmitEOF()
- return b.token
- }
- b.token = nil
- b.channel = TokenDefaultChannel
- b.TokenStartCharIndex = b.input.Index()
- b.TokenStartColumn = b.Interpreter.GetCharPositionInLine()
- b.TokenStartLine = b.Interpreter.GetLine()
- b.text = ""
- continueOuter := false
- for {
- b.thetype = TokenInvalidType
- ttype := LexerSkip
-
- ttype = b.safeMatch()
-
- if b.input.LA(1) == TokenEOF {
- b.hitEOF = true
- }
- if b.thetype == TokenInvalidType {
- b.thetype = ttype
- }
- if b.thetype == LexerSkip {
- continueOuter = true
- break
- }
- if b.thetype != LexerMore {
- break
- }
- }
-
- if continueOuter {
- continue
- }
- if b.token == nil {
- b.Virt.Emit()
- }
- return b.token
- }
-
- return nil
-}
-
-// Instruct the lexer to Skip creating a token for current lexer rule
-// and look for another token. NextToken() knows to keep looking when
-// a lexer rule finishes with token set to SKIPTOKEN. Recall that
-// if token==nil at end of any token rule, it creates one for you
-// and emits it.
-// /
-func (b *BaseLexer) Skip() {
- b.thetype = LexerSkip
-}
-
-func (b *BaseLexer) More() {
- b.thetype = LexerMore
-}
-
-func (b *BaseLexer) SetMode(m int) {
- b.mode = m
-}
-
-func (b *BaseLexer) PushMode(m int) {
- if LexerATNSimulatorDebug {
- fmt.Println("pushMode " + strconv.Itoa(m))
- }
- b.modeStack.Push(b.mode)
- b.mode = m
-}
-
-func (b *BaseLexer) PopMode() int {
- if len(b.modeStack) == 0 {
- panic("Empty Stack")
- }
- if LexerATNSimulatorDebug {
- fmt.Println("popMode back to " + fmt.Sprint(b.modeStack[0:len(b.modeStack)-1]))
- }
- i, _ := b.modeStack.Pop()
- b.mode = i
- return b.mode
-}
-
-func (b *BaseLexer) inputStream() CharStream {
- return b.input
-}
-
-func (b *BaseLexer) setInputStream(input CharStream) {
- b.input = nil
- b.tokenFactorySourcePair = &TokenSourceCharStreamPair{b, b.input}
- b.reset()
- b.input = input
- b.tokenFactorySourcePair = &TokenSourceCharStreamPair{b, b.input}
-}
-
-func (b *BaseLexer) GetTokenSourceCharStreamPair() *TokenSourceCharStreamPair {
- return b.tokenFactorySourcePair
-}
-
-// By default does not support multiple emits per NextToken invocation
-// for efficiency reasons. Subclass and override l method, NextToken,
-// and GetToken (to push tokens into a list and pull from that list
-// rather than a single variable as l implementation does).
-// /
-func (b *BaseLexer) EmitToken(token Token) {
- b.token = token
-}
-
-// The standard method called to automatically emit a token at the
-// outermost lexical rule. The token object should point into the
-// char buffer start..stop. If there is a text override in 'text',
-// use that to set the token's text. Override l method to emit
-// custom Token objects or provide a Newfactory.
-// /
-func (b *BaseLexer) Emit() Token {
- t := b.factory.Create(b.tokenFactorySourcePair, b.thetype, b.text, b.channel, b.TokenStartCharIndex, b.GetCharIndex()-1, b.TokenStartLine, b.TokenStartColumn)
- b.EmitToken(t)
- return t
-}
-
-func (b *BaseLexer) EmitEOF() Token {
- cpos := b.GetCharPositionInLine()
- lpos := b.GetLine()
- eof := b.factory.Create(b.tokenFactorySourcePair, TokenEOF, "", TokenDefaultChannel, b.input.Index(), b.input.Index()-1, lpos, cpos)
- b.EmitToken(eof)
- return eof
-}
-
-func (b *BaseLexer) GetCharPositionInLine() int {
- return b.Interpreter.GetCharPositionInLine()
-}
-
-func (b *BaseLexer) GetLine() int {
- return b.Interpreter.GetLine()
-}
-
-func (b *BaseLexer) GetType() int {
- return b.thetype
-}
-
-func (b *BaseLexer) SetType(t int) {
- b.thetype = t
-}
-
-// What is the index of the current character of lookahead?///
-func (b *BaseLexer) GetCharIndex() int {
- return b.input.Index()
-}
-
-// Return the text Matched so far for the current token or any text override.
-//Set the complete text of l token it wipes any previous changes to the text.
-func (b *BaseLexer) GetText() string {
- if b.text != "" {
- return b.text
- }
-
- return b.Interpreter.GetText(b.input)
-}
-
-func (b *BaseLexer) SetText(text string) {
- b.text = text
-}
-
-func (b *BaseLexer) GetATN() *ATN {
- return b.Interpreter.ATN()
-}
-
-// Return a list of all Token objects in input char stream.
-// Forces load of all tokens. Does not include EOF token.
-// /
-func (b *BaseLexer) GetAllTokens() []Token {
- vl := b.Virt
- tokens := make([]Token, 0)
- t := vl.NextToken()
- for t.GetTokenType() != TokenEOF {
- tokens = append(tokens, t)
- t = vl.NextToken()
- }
- return tokens
-}
-
-func (b *BaseLexer) notifyListeners(e RecognitionException) {
- start := b.TokenStartCharIndex
- stop := b.input.Index()
- text := b.input.GetTextFromInterval(NewInterval(start, stop))
- msg := "token recognition error at: '" + text + "'"
- listener := b.GetErrorListenerDispatch()
- listener.SyntaxError(b, nil, b.TokenStartLine, b.TokenStartColumn, msg, e)
-}
-
-func (b *BaseLexer) getErrorDisplayForChar(c rune) string {
- if c == TokenEOF {
- return ""
- } else if c == '\n' {
- return "\\n"
- } else if c == '\t' {
- return "\\t"
- } else if c == '\r' {
- return "\\r"
- } else {
- return string(c)
- }
-}
-
-func (b *BaseLexer) getCharErrorDisplay(c rune) string {
- return "'" + b.getErrorDisplayForChar(c) + "'"
-}
-
-// Lexers can normally Match any char in it's vocabulary after Matching
-// a token, so do the easy thing and just kill a character and hope
-// it all works out. You can instead use the rule invocation stack
-// to do sophisticated error recovery if you are in a fragment rule.
-// /
-func (b *BaseLexer) Recover(re RecognitionException) {
- if b.input.LA(1) != TokenEOF {
- if _, ok := re.(*LexerNoViableAltException); ok {
- // Skip a char and try again
- b.Interpreter.Consume(b.input)
- } else {
- // TODO: Do we lose character or line position information?
- b.input.Consume()
- }
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action.go
deleted file mode 100644
index 20df84f..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action.go
+++ /dev/null
@@ -1,431 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import "strconv"
-
-const (
- LexerActionTypeChannel = 0 //The type of a {@link LexerChannelAction} action.
- LexerActionTypeCustom = 1 //The type of a {@link LexerCustomAction} action.
- LexerActionTypeMode = 2 //The type of a {@link LexerModeAction} action.
- LexerActionTypeMore = 3 //The type of a {@link LexerMoreAction} action.
- LexerActionTypePopMode = 4 //The type of a {@link LexerPopModeAction} action.
- LexerActionTypePushMode = 5 //The type of a {@link LexerPushModeAction} action.
- LexerActionTypeSkip = 6 //The type of a {@link LexerSkipAction} action.
- LexerActionTypeType = 7 //The type of a {@link LexerTypeAction} action.
-)
-
-type LexerAction interface {
- getActionType() int
- getIsPositionDependent() bool
- execute(lexer Lexer)
- hash() int
- equals(other LexerAction) bool
-}
-
-type BaseLexerAction struct {
- actionType int
- isPositionDependent bool
-}
-
-func NewBaseLexerAction(action int) *BaseLexerAction {
- la := new(BaseLexerAction)
-
- la.actionType = action
- la.isPositionDependent = false
-
- return la
-}
-
-func (b *BaseLexerAction) execute(lexer Lexer) {
- panic("Not implemented")
-}
-
-func (b *BaseLexerAction) getActionType() int {
- return b.actionType
-}
-
-func (b *BaseLexerAction) getIsPositionDependent() bool {
- return b.isPositionDependent
-}
-
-func (b *BaseLexerAction) hash() int {
- return b.actionType
-}
-
-func (b *BaseLexerAction) equals(other LexerAction) bool {
- return b == other
-}
-
-//
-// Implements the {@code Skip} lexer action by calling {@link Lexer//Skip}.
-//
-// The {@code Skip} command does not have any parameters, so l action is
-// implemented as a singleton instance exposed by {@link //INSTANCE}.
-type LexerSkipAction struct {
- *BaseLexerAction
-}
-
-func NewLexerSkipAction() *LexerSkipAction {
- la := new(LexerSkipAction)
- la.BaseLexerAction = NewBaseLexerAction(LexerActionTypeSkip)
- return la
-}
-
-// Provides a singleton instance of l parameterless lexer action.
-var LexerSkipActionINSTANCE = NewLexerSkipAction()
-
-func (l *LexerSkipAction) execute(lexer Lexer) {
- lexer.Skip()
-}
-
-func (l *LexerSkipAction) String() string {
- return "skip"
-}
-
-// Implements the {@code type} lexer action by calling {@link Lexer//setType}
-// with the assigned type.
-type LexerTypeAction struct {
- *BaseLexerAction
-
- thetype int
-}
-
-func NewLexerTypeAction(thetype int) *LexerTypeAction {
- l := new(LexerTypeAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypeType)
- l.thetype = thetype
- return l
-}
-
-func (l *LexerTypeAction) execute(lexer Lexer) {
- lexer.SetType(l.thetype)
-}
-
-func (l *LexerTypeAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.thetype)
- return murmurFinish(h, 2)
-}
-
-func (l *LexerTypeAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerTypeAction); !ok {
- return false
- } else {
- return l.thetype == other.(*LexerTypeAction).thetype
- }
-}
-
-func (l *LexerTypeAction) String() string {
- return "actionType(" + strconv.Itoa(l.thetype) + ")"
-}
-
-// Implements the {@code pushMode} lexer action by calling
-// {@link Lexer//pushMode} with the assigned mode.
-type LexerPushModeAction struct {
- *BaseLexerAction
-
- mode int
-}
-
-func NewLexerPushModeAction(mode int) *LexerPushModeAction {
-
- l := new(LexerPushModeAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypePushMode)
-
- l.mode = mode
- return l
-}
-
-// This action is implemented by calling {@link Lexer//pushMode} with the
-// value provided by {@link //getMode}.
-func (l *LexerPushModeAction) execute(lexer Lexer) {
- lexer.PushMode(l.mode)
-}
-
-func (l *LexerPushModeAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.mode)
- return murmurFinish(h, 2)
-}
-
-func (l *LexerPushModeAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerPushModeAction); !ok {
- return false
- } else {
- return l.mode == other.(*LexerPushModeAction).mode
- }
-}
-
-func (l *LexerPushModeAction) String() string {
- return "pushMode(" + strconv.Itoa(l.mode) + ")"
-}
-
-// Implements the {@code popMode} lexer action by calling {@link Lexer//popMode}.
-//
-// The {@code popMode} command does not have any parameters, so l action is
-// implemented as a singleton instance exposed by {@link //INSTANCE}.
-type LexerPopModeAction struct {
- *BaseLexerAction
-}
-
-func NewLexerPopModeAction() *LexerPopModeAction {
-
- l := new(LexerPopModeAction)
-
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypePopMode)
-
- return l
-}
-
-var LexerPopModeActionINSTANCE = NewLexerPopModeAction()
-
-// This action is implemented by calling {@link Lexer//popMode}.
-func (l *LexerPopModeAction) execute(lexer Lexer) {
- lexer.PopMode()
-}
-
-func (l *LexerPopModeAction) String() string {
- return "popMode"
-}
-
-// Implements the {@code more} lexer action by calling {@link Lexer//more}.
-//
-// The {@code more} command does not have any parameters, so l action is
-// implemented as a singleton instance exposed by {@link //INSTANCE}.
-
-type LexerMoreAction struct {
- *BaseLexerAction
-}
-
-func NewLexerMoreAction() *LexerMoreAction {
- l := new(LexerMoreAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypeMore)
-
- return l
-}
-
-var LexerMoreActionINSTANCE = NewLexerMoreAction()
-
-// This action is implemented by calling {@link Lexer//popMode}.
-func (l *LexerMoreAction) execute(lexer Lexer) {
- lexer.More()
-}
-
-func (l *LexerMoreAction) String() string {
- return "more"
-}
-
-// Implements the {@code mode} lexer action by calling {@link Lexer//mode} with
-// the assigned mode.
-type LexerModeAction struct {
- *BaseLexerAction
-
- mode int
-}
-
-func NewLexerModeAction(mode int) *LexerModeAction {
- l := new(LexerModeAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypeMode)
- l.mode = mode
- return l
-}
-
-// This action is implemented by calling {@link Lexer//mode} with the
-// value provided by {@link //getMode}.
-func (l *LexerModeAction) execute(lexer Lexer) {
- lexer.SetMode(l.mode)
-}
-
-func (l *LexerModeAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.mode)
- return murmurFinish(h, 2)
-}
-
-func (l *LexerModeAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerModeAction); !ok {
- return false
- } else {
- return l.mode == other.(*LexerModeAction).mode
- }
-}
-
-func (l *LexerModeAction) String() string {
- return "mode(" + strconv.Itoa(l.mode) + ")"
-}
-
-// Executes a custom lexer action by calling {@link Recognizer//action} with the
-// rule and action indexes assigned to the custom action. The implementation of
-// a custom action is added to the generated code for the lexer in an override
-// of {@link Recognizer//action} when the grammar is compiled.
-//
-// This class may represent embedded actions created with the {...}
-// syntax in ANTLR 4, as well as actions created for lexer commands where the
-// command argument could not be evaluated when the grammar was compiled.
-
-// Constructs a custom lexer action with the specified rule and action
-// indexes.
-//
-// @param ruleIndex The rule index to use for calls to
-// {@link Recognizer//action}.
-// @param actionIndex The action index to use for calls to
-// {@link Recognizer//action}.
-
-type LexerCustomAction struct {
- *BaseLexerAction
- ruleIndex, actionIndex int
-}
-
-func NewLexerCustomAction(ruleIndex, actionIndex int) *LexerCustomAction {
- l := new(LexerCustomAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypeCustom)
- l.ruleIndex = ruleIndex
- l.actionIndex = actionIndex
- l.isPositionDependent = true
- return l
-}
-
-// Custom actions are implemented by calling {@link Lexer//action} with the
-// appropriate rule and action indexes.
-func (l *LexerCustomAction) execute(lexer Lexer) {
- lexer.Action(nil, l.ruleIndex, l.actionIndex)
-}
-
-func (l *LexerCustomAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.ruleIndex)
- h = murmurUpdate(h, l.actionIndex)
- return murmurFinish(h, 3)
-}
-
-func (l *LexerCustomAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerCustomAction); !ok {
- return false
- } else {
- return l.ruleIndex == other.(*LexerCustomAction).ruleIndex && l.actionIndex == other.(*LexerCustomAction).actionIndex
- }
-}
-
-// Implements the {@code channel} lexer action by calling
-// {@link Lexer//setChannel} with the assigned channel.
-// Constructs a New{@code channel} action with the specified channel value.
-// @param channel The channel value to pass to {@link Lexer//setChannel}.
-type LexerChannelAction struct {
- *BaseLexerAction
-
- channel int
-}
-
-func NewLexerChannelAction(channel int) *LexerChannelAction {
- l := new(LexerChannelAction)
- l.BaseLexerAction = NewBaseLexerAction(LexerActionTypeChannel)
- l.channel = channel
- return l
-}
-
-// This action is implemented by calling {@link Lexer//setChannel} with the
-// value provided by {@link //getChannel}.
-func (l *LexerChannelAction) execute(lexer Lexer) {
- lexer.SetChannel(l.channel)
-}
-
-func (l *LexerChannelAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.channel)
- return murmurFinish(h, 2)
-}
-
-func (l *LexerChannelAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerChannelAction); !ok {
- return false
- } else {
- return l.channel == other.(*LexerChannelAction).channel
- }
-}
-
-func (l *LexerChannelAction) String() string {
- return "channel(" + strconv.Itoa(l.channel) + ")"
-}
-
-// This implementation of {@link LexerAction} is used for tracking input offsets
-// for position-dependent actions within a {@link LexerActionExecutor}.
-//
-// This action is not serialized as part of the ATN, and is only required for
-// position-dependent lexer actions which appear at a location other than the
-// end of a rule. For more information about DFA optimizations employed for
-// lexer actions, see {@link LexerActionExecutor//append} and
-// {@link LexerActionExecutor//fixOffsetBeforeMatch}.
-
-// Constructs a Newindexed custom action by associating a character offset
-// with a {@link LexerAction}.
-//
-// Note: This class is only required for lexer actions for which
-// {@link LexerAction//isPositionDependent} returns {@code true}.
-//
-// @param offset The offset into the input {@link CharStream}, relative to
-// the token start index, at which the specified lexer action should be
-// executed.
-// @param action The lexer action to execute at a particular offset in the
-// input {@link CharStream}.
-type LexerIndexedCustomAction struct {
- *BaseLexerAction
-
- offset int
- lexerAction LexerAction
- isPositionDependent bool
-}
-
-func NewLexerIndexedCustomAction(offset int, lexerAction LexerAction) *LexerIndexedCustomAction {
-
- l := new(LexerIndexedCustomAction)
- l.BaseLexerAction = NewBaseLexerAction(lexerAction.getActionType())
-
- l.offset = offset
- l.lexerAction = lexerAction
- l.isPositionDependent = true
-
- return l
-}
-
-// This method calls {@link //execute} on the result of {@link //getAction}
-// using the provided {@code lexer}.
-func (l *LexerIndexedCustomAction) execute(lexer Lexer) {
- // assume the input stream position was properly set by the calling code
- l.lexerAction.execute(lexer)
-}
-
-func (l *LexerIndexedCustomAction) hash() int {
- h := murmurInit(0)
- h = murmurUpdate(h, l.actionType)
- h = murmurUpdate(h, l.offset)
- h = murmurUpdate(h, l.lexerAction.hash())
- return murmurFinish(h, 3)
-}
-
-func (l *LexerIndexedCustomAction) equals(other LexerAction) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerIndexedCustomAction); !ok {
- return false
- } else {
- return l.offset == other.(*LexerIndexedCustomAction).offset && l.lexerAction == other.(*LexerIndexedCustomAction).lexerAction
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action_executor.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action_executor.go
deleted file mode 100644
index 80b949a..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_action_executor.go
+++ /dev/null
@@ -1,170 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// Represents an executor for a sequence of lexer actions which traversed during
-// the Matching operation of a lexer rule (token).
-//
-// The executor tracks position information for position-dependent lexer actions
-// efficiently, ensuring that actions appearing only at the end of the rule do
-// not cause bloating of the {@link DFA} created for the lexer.
-
-type LexerActionExecutor struct {
- lexerActions []LexerAction
- cachedHash int
-}
-
-func NewLexerActionExecutor(lexerActions []LexerAction) *LexerActionExecutor {
-
- if lexerActions == nil {
- lexerActions = make([]LexerAction, 0)
- }
-
- l := new(LexerActionExecutor)
-
- l.lexerActions = lexerActions
-
- // Caches the result of {@link //hashCode} since the hash code is an element
- // of the performance-critical {@link LexerATNConfig//hashCode} operation.
- l.cachedHash = murmurInit(57)
- for _, a := range lexerActions {
- l.cachedHash = murmurUpdate(l.cachedHash, a.hash())
- }
-
- return l
-}
-
-// Creates a {@link LexerActionExecutor} which executes the actions for
-// the input {@code lexerActionExecutor} followed by a specified
-// {@code lexerAction}.
-//
-// @param lexerActionExecutor The executor for actions already traversed by
-// the lexer while Matching a token within a particular
-// {@link LexerATNConfig}. If this is {@code nil}, the method behaves as
-// though it were an empty executor.
-// @param lexerAction The lexer action to execute after the actions
-// specified in {@code lexerActionExecutor}.
-//
-// @return A {@link LexerActionExecutor} for executing the combine actions
-// of {@code lexerActionExecutor} and {@code lexerAction}.
-func LexerActionExecutorappend(lexerActionExecutor *LexerActionExecutor, lexerAction LexerAction) *LexerActionExecutor {
- if lexerActionExecutor == nil {
- return NewLexerActionExecutor([]LexerAction{lexerAction})
- }
-
- return NewLexerActionExecutor(append(lexerActionExecutor.lexerActions, lexerAction))
-}
-
-// Creates a {@link LexerActionExecutor} which encodes the current offset
-// for position-dependent lexer actions.
-//
-// Normally, when the executor encounters lexer actions where
-// {@link LexerAction//isPositionDependent} returns {@code true}, it calls
-// {@link IntStream//seek} on the input {@link CharStream} to set the input
-// position to the end of the current token. This behavior provides
-// for efficient DFA representation of lexer actions which appear at the end
-// of a lexer rule, even when the lexer rule Matches a variable number of
-// characters.
-//
-// Prior to traversing a Match transition in the ATN, the current offset
-// from the token start index is assigned to all position-dependent lexer
-// actions which have not already been assigned a fixed offset. By storing
-// the offsets relative to the token start index, the DFA representation of
-// lexer actions which appear in the middle of tokens remains efficient due
-// to sharing among tokens of the same length, regardless of their absolute
-// position in the input stream.
-//
-// If the current executor already has offsets assigned to all
-// position-dependent lexer actions, the method returns {@code this}.
-//
-// @param offset The current offset to assign to all position-dependent
-// lexer actions which do not already have offsets assigned.
-//
-// @return A {@link LexerActionExecutor} which stores input stream offsets
-// for all position-dependent lexer actions.
-// /
-func (l *LexerActionExecutor) fixOffsetBeforeMatch(offset int) *LexerActionExecutor {
- var updatedLexerActions []LexerAction
- for i := 0; i < len(l.lexerActions); i++ {
- _, ok := l.lexerActions[i].(*LexerIndexedCustomAction)
- if l.lexerActions[i].getIsPositionDependent() && !ok {
- if updatedLexerActions == nil {
- updatedLexerActions = make([]LexerAction, 0)
-
- for _, a := range l.lexerActions {
- updatedLexerActions = append(updatedLexerActions, a)
- }
- }
-
- updatedLexerActions[i] = NewLexerIndexedCustomAction(offset, l.lexerActions[i])
- }
- }
- if updatedLexerActions == nil {
- return l
- }
-
- return NewLexerActionExecutor(updatedLexerActions)
-}
-
-// Execute the actions encapsulated by l executor within the context of a
-// particular {@link Lexer}.
-//
-// This method calls {@link IntStream//seek} to set the position of the
-// {@code input} {@link CharStream} prior to calling
-// {@link LexerAction//execute} on a position-dependent action. Before the
-// method returns, the input position will be restored to the same position
-// it was in when the method was invoked.
-//
-// @param lexer The lexer instance.
-// @param input The input stream which is the source for the current token.
-// When l method is called, the current {@link IntStream//index} for
-// {@code input} should be the start of the following token, i.e. 1
-// character past the end of the current token.
-// @param startIndex The token start index. This value may be passed to
-// {@link IntStream//seek} to set the {@code input} position to the beginning
-// of the token.
-// /
-func (l *LexerActionExecutor) execute(lexer Lexer, input CharStream, startIndex int) {
- requiresSeek := false
- stopIndex := input.Index()
-
- defer func() {
- if requiresSeek {
- input.Seek(stopIndex)
- }
- }()
-
- for i := 0; i < len(l.lexerActions); i++ {
- lexerAction := l.lexerActions[i]
- if la, ok := lexerAction.(*LexerIndexedCustomAction); ok {
- offset := la.offset
- input.Seek(startIndex + offset)
- lexerAction = la.lexerAction
- requiresSeek = (startIndex + offset) != stopIndex
- } else if lexerAction.getIsPositionDependent() {
- input.Seek(stopIndex)
- requiresSeek = false
- }
- lexerAction.execute(lexer)
- }
-}
-
-func (l *LexerActionExecutor) hash() int {
- if l == nil {
- return 61
- }
- return l.cachedHash
-}
-
-func (l *LexerActionExecutor) equals(other interface{}) bool {
- if l == other {
- return true
- } else if _, ok := other.(*LexerActionExecutor); !ok {
- return false
- } else {
- return l.cachedHash == other.(*LexerActionExecutor).cachedHash &&
- &l.lexerActions == &other.(*LexerActionExecutor).lexerActions
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_atn_simulator.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_atn_simulator.go
deleted file mode 100644
index 131364f..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/lexer_atn_simulator.go
+++ /dev/null
@@ -1,658 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
-)
-
-var (
- LexerATNSimulatorDebug = false
- LexerATNSimulatorDFADebug = false
-
- LexerATNSimulatorMinDFAEdge = 0
- LexerATNSimulatorMaxDFAEdge = 127 // forces unicode to stay in ATN
-
- LexerATNSimulatorMatchCalls = 0
-)
-
-type ILexerATNSimulator interface {
- IATNSimulator
-
- reset()
- Match(input CharStream, mode int) int
- GetCharPositionInLine() int
- GetLine() int
- GetText(input CharStream) string
- Consume(input CharStream)
-}
-
-type LexerATNSimulator struct {
- *BaseATNSimulator
-
- recog Lexer
- predictionMode int
- mergeCache DoubleDict
- startIndex int
- Line int
- CharPositionInLine int
- mode int
- prevAccept *SimState
- MatchCalls int
-}
-
-func NewLexerATNSimulator(recog Lexer, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *LexerATNSimulator {
- l := new(LexerATNSimulator)
-
- l.BaseATNSimulator = NewBaseATNSimulator(atn, sharedContextCache)
-
- l.decisionToDFA = decisionToDFA
- l.recog = recog
- // The current token's starting index into the character stream.
- // Shared across DFA to ATN simulation in case the ATN fails and the
- // DFA did not have a previous accept state. In l case, we use the
- // ATN-generated exception object.
- l.startIndex = -1
- // line number 1..n within the input///
- l.Line = 1
- // The index of the character relative to the beginning of the line
- // 0..n-1///
- l.CharPositionInLine = 0
- l.mode = LexerDefaultMode
- // Used during DFA/ATN exec to record the most recent accept configuration
- // info
- l.prevAccept = NewSimState()
- // done
- return l
-}
-
-func (l *LexerATNSimulator) copyState(simulator *LexerATNSimulator) {
- l.CharPositionInLine = simulator.CharPositionInLine
- l.Line = simulator.Line
- l.mode = simulator.mode
- l.startIndex = simulator.startIndex
-}
-
-func (l *LexerATNSimulator) Match(input CharStream, mode int) int {
- l.MatchCalls++
- l.mode = mode
- mark := input.Mark()
-
- defer func() {
- input.Release(mark)
- }()
-
- l.startIndex = input.Index()
- l.prevAccept.reset()
-
- dfa := l.decisionToDFA[mode]
-
- if dfa.s0 == nil {
- return l.MatchATN(input)
- }
-
- return l.execATN(input, dfa.s0)
-}
-
-func (l *LexerATNSimulator) reset() {
- l.prevAccept.reset()
- l.startIndex = -1
- l.Line = 1
- l.CharPositionInLine = 0
- l.mode = LexerDefaultMode
-}
-
-func (l *LexerATNSimulator) MatchATN(input CharStream) int {
- startState := l.atn.modeToStartState[l.mode]
-
- if LexerATNSimulatorDebug {
- fmt.Println("MatchATN mode " + strconv.Itoa(l.mode) + " start: " + startState.String())
- }
- oldMode := l.mode
- s0Closure := l.computeStartState(input, startState)
- suppressEdge := s0Closure.hasSemanticContext
- s0Closure.hasSemanticContext = false
-
- next := l.addDFAState(s0Closure)
-
- if !suppressEdge {
- l.decisionToDFA[l.mode].setS0(next)
- }
-
- predict := l.execATN(input, next)
-
- if LexerATNSimulatorDebug {
- fmt.Println("DFA after MatchATN: " + l.decisionToDFA[oldMode].ToLexerString())
- }
- return predict
-}
-
-func (l *LexerATNSimulator) execATN(input CharStream, ds0 *DFAState) int {
-
- if LexerATNSimulatorDebug {
- fmt.Println("start state closure=" + ds0.configs.String())
- }
- if ds0.isAcceptState {
- // allow zero-length tokens
- l.captureSimState(l.prevAccept, input, ds0)
- }
- t := input.LA(1)
- s := ds0 // s is current/from DFA state
-
- for { // while more work
- if LexerATNSimulatorDebug {
- fmt.Println("execATN loop starting closure: " + s.configs.String())
- }
-
- // As we move src->trg, src->trg, we keep track of the previous trg to
- // avoid looking up the DFA state again, which is expensive.
- // If the previous target was already part of the DFA, we might
- // be able to avoid doing a reach operation upon t. If s!=nil,
- // it means that semantic predicates didn't prevent us from
- // creating a DFA state. Once we know s!=nil, we check to see if
- // the DFA state has an edge already for t. If so, we can just reuse
- // it's configuration set there's no point in re-computing it.
- // This is kind of like doing DFA simulation within the ATN
- // simulation because DFA simulation is really just a way to avoid
- // computing reach/closure sets. Technically, once we know that
- // we have a previously added DFA state, we could jump over to
- // the DFA simulator. But, that would mean popping back and forth
- // a lot and making things more complicated algorithmically.
- // This optimization makes a lot of sense for loops within DFA.
- // A character will take us back to an existing DFA state
- // that already has lots of edges out of it. e.g., .* in comments.
- target := l.getExistingTargetState(s, t)
- if target == nil {
- target = l.computeTargetState(input, s, t)
- // print("Computed:" + str(target))
- }
- if target == ATNSimulatorError {
- break
- }
- // If l is a consumable input element, make sure to consume before
- // capturing the accept state so the input index, line, and char
- // position accurately reflect the state of the interpreter at the
- // end of the token.
- if t != TokenEOF {
- l.Consume(input)
- }
- if target.isAcceptState {
- l.captureSimState(l.prevAccept, input, target)
- if t == TokenEOF {
- break
- }
- }
- t = input.LA(1)
- s = target // flip current DFA target becomes Newsrc/from state
- }
-
- return l.failOrAccept(l.prevAccept, input, s.configs, t)
-}
-
-// Get an existing target state for an edge in the DFA. If the target state
-// for the edge has not yet been computed or is otherwise not available,
-// l method returns {@code nil}.
-//
-// @param s The current DFA state
-// @param t The next input symbol
-// @return The existing target DFA state for the given input symbol
-// {@code t}, or {@code nil} if the target state for l edge is not
-// already cached
-func (l *LexerATNSimulator) getExistingTargetState(s *DFAState, t int) *DFAState {
- if s.edges == nil || t < LexerATNSimulatorMinDFAEdge || t > LexerATNSimulatorMaxDFAEdge {
- return nil
- }
-
- target := s.edges[t-LexerATNSimulatorMinDFAEdge]
- if LexerATNSimulatorDebug && target != nil {
- fmt.Println("reuse state " + strconv.Itoa(s.stateNumber) + " edge to " + strconv.Itoa(target.stateNumber))
- }
- return target
-}
-
-// Compute a target state for an edge in the DFA, and attempt to add the
-// computed state and corresponding edge to the DFA.
-//
-// @param input The input stream
-// @param s The current DFA state
-// @param t The next input symbol
-//
-// @return The computed target DFA state for the given input symbol
-// {@code t}. If {@code t} does not lead to a valid DFA state, l method
-// returns {@link //ERROR}.
-func (l *LexerATNSimulator) computeTargetState(input CharStream, s *DFAState, t int) *DFAState {
- reach := NewOrderedATNConfigSet()
-
- // if we don't find an existing DFA state
- // Fill reach starting from closure, following t transitions
- l.getReachableConfigSet(input, s.configs, reach.BaseATNConfigSet, t)
-
- if len(reach.configs) == 0 { // we got nowhere on t from s
- if !reach.hasSemanticContext {
- // we got nowhere on t, don't panic out l knowledge it'd
- // cause a failover from DFA later.
- l.addDFAEdge(s, t, ATNSimulatorError, nil)
- }
- // stop when we can't Match any more char
- return ATNSimulatorError
- }
- // Add an edge from s to target DFA found/created for reach
- return l.addDFAEdge(s, t, nil, reach.BaseATNConfigSet)
-}
-
-func (l *LexerATNSimulator) failOrAccept(prevAccept *SimState, input CharStream, reach ATNConfigSet, t int) int {
- if l.prevAccept.dfaState != nil {
- lexerActionExecutor := prevAccept.dfaState.lexerActionExecutor
- l.accept(input, lexerActionExecutor, l.startIndex, prevAccept.index, prevAccept.line, prevAccept.column)
- return prevAccept.dfaState.prediction
- }
-
- // if no accept and EOF is first char, return EOF
- if t == TokenEOF && input.Index() == l.startIndex {
- return TokenEOF
- }
-
- panic(NewLexerNoViableAltException(l.recog, input, l.startIndex, reach))
-}
-
-// Given a starting configuration set, figure out all ATN configurations
-// we can reach upon input {@code t}. Parameter {@code reach} is a return
-// parameter.
-func (l *LexerATNSimulator) getReachableConfigSet(input CharStream, closure ATNConfigSet, reach ATNConfigSet, t int) {
- // l is used to Skip processing for configs which have a lower priority
- // than a config that already reached an accept state for the same rule
- SkipAlt := ATNInvalidAltNumber
-
- for _, cfg := range closure.GetItems() {
- currentAltReachedAcceptState := (cfg.GetAlt() == SkipAlt)
- if currentAltReachedAcceptState && cfg.(*LexerATNConfig).passedThroughNonGreedyDecision {
- continue
- }
-
- if LexerATNSimulatorDebug {
-
- fmt.Printf("testing %s at %s\n", l.GetTokenName(t), cfg.String()) // l.recog, true))
- }
-
- for _, trans := range cfg.GetState().GetTransitions() {
- target := l.getReachableTarget(trans, t)
- if target != nil {
- lexerActionExecutor := cfg.(*LexerATNConfig).lexerActionExecutor
- if lexerActionExecutor != nil {
- lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.Index() - l.startIndex)
- }
- treatEOFAsEpsilon := (t == TokenEOF)
- config := NewLexerATNConfig3(cfg.(*LexerATNConfig), target, lexerActionExecutor)
- if l.closure(input, config, reach,
- currentAltReachedAcceptState, true, treatEOFAsEpsilon) {
- // any remaining configs for l alt have a lower priority
- // than the one that just reached an accept state.
- SkipAlt = cfg.GetAlt()
- }
- }
- }
- }
-}
-
-func (l *LexerATNSimulator) accept(input CharStream, lexerActionExecutor *LexerActionExecutor, startIndex, index, line, charPos int) {
- if LexerATNSimulatorDebug {
- fmt.Printf("ACTION %s\n", lexerActionExecutor)
- }
- // seek to after last char in token
- input.Seek(index)
- l.Line = line
- l.CharPositionInLine = charPos
- if lexerActionExecutor != nil && l.recog != nil {
- lexerActionExecutor.execute(l.recog, input, startIndex)
- }
-}
-
-func (l *LexerATNSimulator) getReachableTarget(trans Transition, t int) ATNState {
- if trans.Matches(t, 0, LexerMaxCharValue) {
- return trans.getTarget()
- }
-
- return nil
-}
-
-func (l *LexerATNSimulator) computeStartState(input CharStream, p ATNState) *OrderedATNConfigSet {
- configs := NewOrderedATNConfigSet()
- for i := 0; i < len(p.GetTransitions()); i++ {
- target := p.GetTransitions()[i].getTarget()
- cfg := NewLexerATNConfig6(target, i+1, BasePredictionContextEMPTY)
- l.closure(input, cfg, configs, false, false, false)
- }
-
- return configs
-}
-
-// Since the alternatives within any lexer decision are ordered by
-// preference, l method stops pursuing the closure as soon as an accept
-// state is reached. After the first accept state is reached by depth-first
-// search from {@code config}, all other (potentially reachable) states for
-// l rule would have a lower priority.
-//
-// @return {@code true} if an accept state is reached, otherwise
-// {@code false}.
-func (l *LexerATNSimulator) closure(input CharStream, config *LexerATNConfig, configs ATNConfigSet,
- currentAltReachedAcceptState, speculative, treatEOFAsEpsilon bool) bool {
-
- if LexerATNSimulatorDebug {
- fmt.Println("closure(" + config.String() + ")") // config.String(l.recog, true) + ")")
- }
-
- _, ok := config.state.(*RuleStopState)
- if ok {
-
- if LexerATNSimulatorDebug {
- if l.recog != nil {
- fmt.Printf("closure at %s rule stop %s\n", l.recog.GetRuleNames()[config.state.GetRuleIndex()], config)
- } else {
- fmt.Printf("closure at rule stop %s\n", config)
- }
- }
-
- if config.context == nil || config.context.hasEmptyPath() {
- if config.context == nil || config.context.isEmpty() {
- configs.Add(config, nil)
- return true
- }
-
- configs.Add(NewLexerATNConfig2(config, config.state, BasePredictionContextEMPTY), nil)
- currentAltReachedAcceptState = true
- }
- if config.context != nil && !config.context.isEmpty() {
- for i := 0; i < config.context.length(); i++ {
- if config.context.getReturnState(i) != BasePredictionContextEmptyReturnState {
- newContext := config.context.GetParent(i) // "pop" return state
- returnState := l.atn.states[config.context.getReturnState(i)]
- cfg := NewLexerATNConfig2(config, returnState, newContext)
- currentAltReachedAcceptState = l.closure(input, cfg, configs, currentAltReachedAcceptState, speculative, treatEOFAsEpsilon)
- }
- }
- }
- return currentAltReachedAcceptState
- }
- // optimization
- if !config.state.GetEpsilonOnlyTransitions() {
- if !currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision {
- configs.Add(config, nil)
- }
- }
- for j := 0; j < len(config.state.GetTransitions()); j++ {
- trans := config.state.GetTransitions()[j]
- cfg := l.getEpsilonTarget(input, config, trans, configs, speculative, treatEOFAsEpsilon)
- if cfg != nil {
- currentAltReachedAcceptState = l.closure(input, cfg, configs,
- currentAltReachedAcceptState, speculative, treatEOFAsEpsilon)
- }
- }
- return currentAltReachedAcceptState
-}
-
-// side-effect: can alter configs.hasSemanticContext
-func (l *LexerATNSimulator) getEpsilonTarget(input CharStream, config *LexerATNConfig, trans Transition,
- configs ATNConfigSet, speculative, treatEOFAsEpsilon bool) *LexerATNConfig {
-
- var cfg *LexerATNConfig
-
- if trans.getSerializationType() == TransitionRULE {
-
- rt := trans.(*RuleTransition)
- newContext := SingletonBasePredictionContextCreate(config.context, rt.followState.GetStateNumber())
- cfg = NewLexerATNConfig2(config, trans.getTarget(), newContext)
-
- } else if trans.getSerializationType() == TransitionPRECEDENCE {
- panic("Precedence predicates are not supported in lexers.")
- } else if trans.getSerializationType() == TransitionPREDICATE {
- // Track traversing semantic predicates. If we traverse,
- // we cannot add a DFA state for l "reach" computation
- // because the DFA would not test the predicate again in the
- // future. Rather than creating collections of semantic predicates
- // like v3 and testing them on prediction, v4 will test them on the
- // fly all the time using the ATN not the DFA. This is slower but
- // semantically it's not used that often. One of the key elements to
- // l predicate mechanism is not adding DFA states that see
- // predicates immediately afterwards in the ATN. For example,
-
- // a : ID {p1}? | ID {p2}?
-
- // should create the start state for rule 'a' (to save start state
- // competition), but should not create target of ID state. The
- // collection of ATN states the following ID references includes
- // states reached by traversing predicates. Since l is when we
- // test them, we cannot cash the DFA state target of ID.
-
- pt := trans.(*PredicateTransition)
-
- if LexerATNSimulatorDebug {
- fmt.Println("EVAL rule " + strconv.Itoa(trans.(*PredicateTransition).ruleIndex) + ":" + strconv.Itoa(pt.predIndex))
- }
- configs.SetHasSemanticContext(true)
- if l.evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative) {
- cfg = NewLexerATNConfig4(config, trans.getTarget())
- }
- } else if trans.getSerializationType() == TransitionACTION {
- if config.context == nil || config.context.hasEmptyPath() {
- // execute actions anywhere in the start rule for a token.
- //
- // TODO: if the entry rule is invoked recursively, some
- // actions may be executed during the recursive call. The
- // problem can appear when hasEmptyPath() is true but
- // isEmpty() is false. In l case, the config needs to be
- // split into two contexts - one with just the empty path
- // and another with everything but the empty path.
- // Unfortunately, the current algorithm does not allow
- // getEpsilonTarget to return two configurations, so
- // additional modifications are needed before we can support
- // the split operation.
- lexerActionExecutor := LexerActionExecutorappend(config.lexerActionExecutor, l.atn.lexerActions[trans.(*ActionTransition).actionIndex])
- cfg = NewLexerATNConfig3(config, trans.getTarget(), lexerActionExecutor)
- } else {
- // ignore actions in referenced rules
- cfg = NewLexerATNConfig4(config, trans.getTarget())
- }
- } else if trans.getSerializationType() == TransitionEPSILON {
- cfg = NewLexerATNConfig4(config, trans.getTarget())
- } else if trans.getSerializationType() == TransitionATOM ||
- trans.getSerializationType() == TransitionRANGE ||
- trans.getSerializationType() == TransitionSET {
- if treatEOFAsEpsilon {
- if trans.Matches(TokenEOF, 0, LexerMaxCharValue) {
- cfg = NewLexerATNConfig4(config, trans.getTarget())
- }
- }
- }
- return cfg
-}
-
-// Evaluate a predicate specified in the lexer.
-//
-// If {@code speculative} is {@code true}, l method was called before
-// {@link //consume} for the Matched character. This method should call
-// {@link //consume} before evaluating the predicate to ensure position
-// sensitive values, including {@link Lexer//GetText}, {@link Lexer//GetLine},
-// and {@link Lexer//getcolumn}, properly reflect the current
-// lexer state. This method should restore {@code input} and the simulator
-// to the original state before returning (i.e. undo the actions made by the
-// call to {@link //consume}.
-//
-// @param input The input stream.
-// @param ruleIndex The rule containing the predicate.
-// @param predIndex The index of the predicate within the rule.
-// @param speculative {@code true} if the current index in {@code input} is
-// one character before the predicate's location.
-//
-// @return {@code true} if the specified predicate evaluates to
-// {@code true}.
-// /
-func (l *LexerATNSimulator) evaluatePredicate(input CharStream, ruleIndex, predIndex int, speculative bool) bool {
- // assume true if no recognizer was provided
- if l.recog == nil {
- return true
- }
- if !speculative {
- return l.recog.Sempred(nil, ruleIndex, predIndex)
- }
- savedcolumn := l.CharPositionInLine
- savedLine := l.Line
- index := input.Index()
- marker := input.Mark()
-
- defer func() {
- l.CharPositionInLine = savedcolumn
- l.Line = savedLine
- input.Seek(index)
- input.Release(marker)
- }()
-
- l.Consume(input)
- return l.recog.Sempred(nil, ruleIndex, predIndex)
-}
-
-func (l *LexerATNSimulator) captureSimState(settings *SimState, input CharStream, dfaState *DFAState) {
- settings.index = input.Index()
- settings.line = l.Line
- settings.column = l.CharPositionInLine
- settings.dfaState = dfaState
-}
-
-func (l *LexerATNSimulator) addDFAEdge(from *DFAState, tk int, to *DFAState, cfgs ATNConfigSet) *DFAState {
- if to == nil && cfgs != nil {
- // leading to l call, ATNConfigSet.hasSemanticContext is used as a
- // marker indicating dynamic predicate evaluation makes l edge
- // dependent on the specific input sequence, so the static edge in the
- // DFA should be omitted. The target DFAState is still created since
- // execATN has the ability to reSynchronize with the DFA state cache
- // following the predicate evaluation step.
- //
- // TJP notes: next time through the DFA, we see a pred again and eval.
- // If that gets us to a previously created (but dangling) DFA
- // state, we can continue in pure DFA mode from there.
- // /
- suppressEdge := cfgs.HasSemanticContext()
- cfgs.SetHasSemanticContext(false)
-
- to = l.addDFAState(cfgs)
-
- if suppressEdge {
- return to
- }
- }
- // add the edge
- if tk < LexerATNSimulatorMinDFAEdge || tk > LexerATNSimulatorMaxDFAEdge {
- // Only track edges within the DFA bounds
- return to
- }
- if LexerATNSimulatorDebug {
- fmt.Println("EDGE " + from.String() + " -> " + to.String() + " upon " + strconv.Itoa(tk))
- }
- if from.edges == nil {
- // make room for tokens 1..n and -1 masquerading as index 0
- from.edges = make([]*DFAState, LexerATNSimulatorMaxDFAEdge-LexerATNSimulatorMinDFAEdge+1)
- }
- from.edges[tk-LexerATNSimulatorMinDFAEdge] = to // connect
-
- return to
-}
-
-// Add a NewDFA state if there isn't one with l set of
-// configurations already. This method also detects the first
-// configuration containing an ATN rule stop state. Later, when
-// traversing the DFA, we will know which rule to accept.
-func (l *LexerATNSimulator) addDFAState(configs ATNConfigSet) *DFAState {
-
- proposed := NewDFAState(-1, configs)
- var firstConfigWithRuleStopState ATNConfig
-
- for _, cfg := range configs.GetItems() {
-
- _, ok := cfg.GetState().(*RuleStopState)
-
- if ok {
- firstConfigWithRuleStopState = cfg
- break
- }
- }
- if firstConfigWithRuleStopState != nil {
- proposed.isAcceptState = true
- proposed.lexerActionExecutor = firstConfigWithRuleStopState.(*LexerATNConfig).lexerActionExecutor
- proposed.setPrediction(l.atn.ruleToTokenType[firstConfigWithRuleStopState.GetState().GetRuleIndex()])
- }
- hash := proposed.hash()
- dfa := l.decisionToDFA[l.mode]
- existing, ok := dfa.getState(hash)
- if ok {
- return existing
- }
- newState := proposed
- newState.stateNumber = dfa.numStates()
- configs.SetReadOnly(true)
- newState.configs = configs
- dfa.setState(hash, newState)
- return newState
-}
-
-func (l *LexerATNSimulator) getDFA(mode int) *DFA {
- return l.decisionToDFA[mode]
-}
-
-// Get the text Matched so far for the current token.
-func (l *LexerATNSimulator) GetText(input CharStream) string {
- // index is first lookahead char, don't include.
- return input.GetTextFromInterval(NewInterval(l.startIndex, input.Index()-1))
-}
-
-func (l *LexerATNSimulator) Consume(input CharStream) {
- curChar := input.LA(1)
- if curChar == int('\n') {
- l.Line++
- l.CharPositionInLine = 0
- } else {
- l.CharPositionInLine++
- }
- input.Consume()
-}
-
-func (l *LexerATNSimulator) GetCharPositionInLine() int {
- return l.CharPositionInLine
-}
-
-func (l *LexerATNSimulator) GetLine() int {
- return l.Line
-}
-
-func (l *LexerATNSimulator) GetTokenName(tt int) string {
- if tt == -1 {
- return "EOF"
- }
-
- return "'" + string(tt) + "'"
-}
-
-func resetSimState(sim *SimState) {
- sim.index = -1
- sim.line = 0
- sim.column = -1
- sim.dfaState = nil
-}
-
-type SimState struct {
- index int
- line int
- column int
- dfaState *DFAState
-}
-
-func NewSimState() *SimState {
- s := new(SimState)
- resetSimState(s)
- return s
-}
-
-func (s *SimState) reset() {
- resetSimState(s)
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/ll1_analyzer.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/ll1_analyzer.go
deleted file mode 100644
index f5afd09..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/ll1_analyzer.go
+++ /dev/null
@@ -1,215 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type LL1Analyzer struct {
- atn *ATN
-}
-
-func NewLL1Analyzer(atn *ATN) *LL1Analyzer {
- la := new(LL1Analyzer)
- la.atn = atn
- return la
-}
-
-//* Special value added to the lookahead sets to indicate that we hit
-// a predicate during analysis if {@code seeThruPreds==false}.
-///
-const (
- LL1AnalyzerHitPred = TokenInvalidType
-)
-
-//*
-// Calculates the SLL(1) expected lookahead set for each outgoing transition
-// of an {@link ATNState}. The returned array has one element for each
-// outgoing transition in {@code s}. If the closure from transition
-// i leads to a semantic predicate before Matching a symbol, the
-// element at index i of the result will be {@code nil}.
-//
-// @param s the ATN state
-// @return the expected symbols for each outgoing transition of {@code s}.
-func (la *LL1Analyzer) getDecisionLookahead(s ATNState) []*IntervalSet {
- if s == nil {
- return nil
- }
- count := len(s.GetTransitions())
- look := make([]*IntervalSet, count)
- for alt := 0; alt < count; alt++ {
- look[alt] = NewIntervalSet()
- lookBusy := NewSet(nil, nil)
- seeThruPreds := false // fail to get lookahead upon pred
- la.look1(s.GetTransitions()[alt].getTarget(), nil, BasePredictionContextEMPTY, look[alt], lookBusy, NewBitSet(), seeThruPreds, false)
- // Wipe out lookahead for la alternative if we found nothing
- // or we had a predicate when we !seeThruPreds
- if look[alt].length() == 0 || look[alt].contains(LL1AnalyzerHitPred) {
- look[alt] = nil
- }
- }
- return look
-}
-
-//*
-// Compute set of tokens that can follow {@code s} in the ATN in the
-// specified {@code ctx}.
-//
-// If {@code ctx} is {@code nil} and the end of the rule containing
-// {@code s} is reached, {@link Token//EPSILON} is added to the result set.
-// If {@code ctx} is not {@code nil} and the end of the outermost rule is
-// reached, {@link Token//EOF} is added to the result set.
-//
-// @param s the ATN state
-// @param stopState the ATN state to stop at. This can be a
-// {@link BlockEndState} to detect epsilon paths through a closure.
-// @param ctx the complete parser context, or {@code nil} if the context
-// should be ignored
-//
-// @return The set of tokens that can follow {@code s} in the ATN in the
-// specified {@code ctx}.
-///
-func (la *LL1Analyzer) Look(s, stopState ATNState, ctx RuleContext) *IntervalSet {
- r := NewIntervalSet()
- seeThruPreds := true // ignore preds get all lookahead
- var lookContext PredictionContext
- if ctx != nil {
- lookContext = predictionContextFromRuleContext(s.GetATN(), ctx)
- }
- la.look1(s, stopState, lookContext, r, NewSet(nil, nil), NewBitSet(), seeThruPreds, true)
- return r
-}
-
-//*
-// Compute set of tokens that can follow {@code s} in the ATN in the
-// specified {@code ctx}.
-//
-// If {@code ctx} is {@code nil} and {@code stopState} or the end of the
-// rule containing {@code s} is reached, {@link Token//EPSILON} is added to
-// the result set. If {@code ctx} is not {@code nil} and {@code addEOF} is
-// {@code true} and {@code stopState} or the end of the outermost rule is
-// reached, {@link Token//EOF} is added to the result set.
-//
-// @param s the ATN state.
-// @param stopState the ATN state to stop at. This can be a
-// {@link BlockEndState} to detect epsilon paths through a closure.
-// @param ctx The outer context, or {@code nil} if the outer context should
-// not be used.
-// @param look The result lookahead set.
-// @param lookBusy A set used for preventing epsilon closures in the ATN
-// from causing a stack overflow. Outside code should pass
-// {@code NewSet} for la argument.
-// @param calledRuleStack A set used for preventing left recursion in the
-// ATN from causing a stack overflow. Outside code should pass
-// {@code NewBitSet()} for la argument.
-// @param seeThruPreds {@code true} to true semantic predicates as
-// implicitly {@code true} and "see through them", otherwise {@code false}
-// to treat semantic predicates as opaque and add {@link //HitPred} to the
-// result if one is encountered.
-// @param addEOF Add {@link Token//EOF} to the result if the end of the
-// outermost context is reached. This parameter has no effect if {@code ctx}
-// is {@code nil}.
-
-func (la *LL1Analyzer) look2(s, stopState ATNState, ctx PredictionContext, look *IntervalSet, lookBusy *Set, calledRuleStack *BitSet, seeThruPreds, addEOF bool, i int) {
-
- returnState := la.atn.states[ctx.getReturnState(i)]
-
- removed := calledRuleStack.contains(returnState.GetRuleIndex())
-
- defer func() {
- if removed {
- calledRuleStack.add(returnState.GetRuleIndex())
- }
- }()
-
- calledRuleStack.remove(returnState.GetRuleIndex())
- la.look1(returnState, stopState, ctx.GetParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
-
-}
-
-func (la *LL1Analyzer) look1(s, stopState ATNState, ctx PredictionContext, look *IntervalSet, lookBusy *Set, calledRuleStack *BitSet, seeThruPreds, addEOF bool) {
-
- c := NewBaseATNConfig6(s, 0, ctx)
-
- if lookBusy.contains(c) {
- return
- }
-
- lookBusy.add(c)
-
- if s == stopState {
- if ctx == nil {
- look.addOne(TokenEpsilon)
- return
- } else if ctx.isEmpty() && addEOF {
- look.addOne(TokenEOF)
- return
- }
- }
-
- _, ok := s.(*RuleStopState)
-
- if ok {
- if ctx == nil {
- look.addOne(TokenEpsilon)
- return
- } else if ctx.isEmpty() && addEOF {
- look.addOne(TokenEOF)
- return
- }
-
- if ctx != BasePredictionContextEMPTY {
- // run thru all possible stack tops in ctx
- for i := 0; i < ctx.length(); i++ {
- returnState := la.atn.states[ctx.getReturnState(i)]
- la.look2(returnState, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF, i)
- }
- return
- }
- }
-
- n := len(s.GetTransitions())
-
- for i := 0; i < n; i++ {
- t := s.GetTransitions()[i]
-
- if t1, ok := t.(*RuleTransition); ok {
- if calledRuleStack.contains(t1.getTarget().GetRuleIndex()) {
- continue
- }
-
- newContext := SingletonBasePredictionContextCreate(ctx, t1.followState.GetStateNumber())
- la.look3(stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF, t1)
- } else if t2, ok := t.(AbstractPredicateTransition); ok {
- if seeThruPreds {
- la.look1(t2.getTarget(), stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
- } else {
- look.addOne(LL1AnalyzerHitPred)
- }
- } else if t.getIsEpsilon() {
- la.look1(t.getTarget(), stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
- } else if _, ok := t.(*WildcardTransition); ok {
- look.addRange(TokenMinUserTokenType, la.atn.maxTokenType)
- } else {
- set := t.getLabel()
- if set != nil {
- if _, ok := t.(*NotSetTransition); ok {
- set = set.complement(TokenMinUserTokenType, la.atn.maxTokenType)
- }
- look.addSet(set)
- }
- }
- }
-}
-
-func (la *LL1Analyzer) look3(stopState ATNState, ctx PredictionContext, look *IntervalSet, lookBusy *Set, calledRuleStack *BitSet, seeThruPreds, addEOF bool, t1 *RuleTransition) {
-
- newContext := SingletonBasePredictionContextCreate(ctx, t1.followState.GetStateNumber())
-
- defer func() {
- calledRuleStack.remove(t1.getTarget().GetRuleIndex())
- }()
-
- calledRuleStack.add(t1.getTarget().GetRuleIndex())
- la.look1(t1.getTarget(), stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF)
-
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser.go
deleted file mode 100644
index fb60258..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser.go
+++ /dev/null
@@ -1,718 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
-)
-
-type Parser interface {
- Recognizer
-
- GetInterpreter() *ParserATNSimulator
-
- GetTokenStream() TokenStream
- GetTokenFactory() TokenFactory
- GetParserRuleContext() ParserRuleContext
- SetParserRuleContext(ParserRuleContext)
- Consume() Token
- GetParseListeners() []ParseTreeListener
-
- GetErrorHandler() ErrorStrategy
- SetErrorHandler(ErrorStrategy)
- GetInputStream() IntStream
- GetCurrentToken() Token
- GetExpectedTokens() *IntervalSet
- NotifyErrorListeners(string, Token, RecognitionException)
- IsExpectedToken(int) bool
- GetPrecedence() int
- GetRuleInvocationStack(ParserRuleContext) []string
-}
-
-type BaseParser struct {
- *BaseRecognizer
-
- Interpreter *ParserATNSimulator
- BuildParseTrees bool
-
- input TokenStream
- errHandler ErrorStrategy
- precedenceStack IntStack
- ctx ParserRuleContext
-
- tracer *TraceListener
- parseListeners []ParseTreeListener
- _SyntaxErrors int
-}
-
-// p.is all the parsing support code essentially most of it is error
-// recovery stuff.//
-func NewBaseParser(input TokenStream) *BaseParser {
-
- p := new(BaseParser)
-
- p.BaseRecognizer = NewBaseRecognizer()
-
- // The input stream.
- p.input = nil
- // The error handling strategy for the parser. The default value is a new
- // instance of {@link DefaultErrorStrategy}.
- p.errHandler = NewDefaultErrorStrategy()
- p.precedenceStack = make([]int, 0)
- p.precedenceStack.Push(0)
- // The {@link ParserRuleContext} object for the currently executing rule.
- // p.is always non-nil during the parsing process.
- p.ctx = nil
- // Specifies whether or not the parser should construct a parse tree during
- // the parsing process. The default value is {@code true}.
- p.BuildParseTrees = true
- // When {@link //setTrace}{@code (true)} is called, a reference to the
- // {@link TraceListener} is stored here so it can be easily removed in a
- // later call to {@link //setTrace}{@code (false)}. The listener itself is
- // implemented as a parser listener so p.field is not directly used by
- // other parser methods.
- p.tracer = nil
- // The list of {@link ParseTreeListener} listeners registered to receive
- // events during the parse.
- p.parseListeners = nil
- // The number of syntax errors Reported during parsing. p.value is
- // incremented each time {@link //NotifyErrorListeners} is called.
- p._SyntaxErrors = 0
- p.SetInputStream(input)
-
- return p
-}
-
-// p.field maps from the serialized ATN string to the deserialized {@link
-// ATN} with
-// bypass alternatives.
-//
-// @see ATNDeserializationOptions//isGenerateRuleBypassTransitions()
-//
-var bypassAltsAtnCache = make(map[string]int)
-
-// reset the parser's state//
-func (p *BaseParser) reset() {
- if p.input != nil {
- p.input.Seek(0)
- }
- p.errHandler.reset(p)
- p.ctx = nil
- p._SyntaxErrors = 0
- p.SetTrace(nil)
- p.precedenceStack = make([]int, 0)
- p.precedenceStack.Push(0)
- if p.Interpreter != nil {
- p.Interpreter.reset()
- }
-}
-
-func (p *BaseParser) GetErrorHandler() ErrorStrategy {
- return p.errHandler
-}
-
-func (p *BaseParser) SetErrorHandler(e ErrorStrategy) {
- p.errHandler = e
-}
-
-// Match current input symbol against {@code ttype}. If the symbol type
-// Matches, {@link ANTLRErrorStrategy//ReportMatch} and {@link //consume} are
-// called to complete the Match process.
-//
-// If the symbol type does not Match,
-// {@link ANTLRErrorStrategy//recoverInline} is called on the current error
-// strategy to attempt recovery. If {@link //getBuildParseTree} is
-// {@code true} and the token index of the symbol returned by
-// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
-// the parse tree by calling {@link ParserRuleContext//addErrorNode}.
-//
-// @param ttype the token type to Match
-// @return the Matched symbol
-// @panics RecognitionException if the current input symbol did not Match
-// {@code ttype} and the error strategy could not recover from the
-// mismatched symbol
-
-func (p *BaseParser) Match(ttype int) Token {
-
- t := p.GetCurrentToken()
-
- if t.GetTokenType() == ttype {
- p.errHandler.ReportMatch(p)
- p.Consume()
- } else {
- t = p.errHandler.RecoverInline(p)
- if p.BuildParseTrees && t.GetTokenIndex() == -1 {
- // we must have conjured up a Newtoken during single token
- // insertion
- // if it's not the current symbol
- p.ctx.AddErrorNode(t)
- }
- }
-
- return t
-}
-
-// Match current input symbol as a wildcard. If the symbol type Matches
-// (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//ReportMatch}
-// and {@link //consume} are called to complete the Match process.
-//
-// If the symbol type does not Match,
-// {@link ANTLRErrorStrategy//recoverInline} is called on the current error
-// strategy to attempt recovery. If {@link //getBuildParseTree} is
-// {@code true} and the token index of the symbol returned by
-// {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
-// the parse tree by calling {@link ParserRuleContext//addErrorNode}.
-//
-// @return the Matched symbol
-// @panics RecognitionException if the current input symbol did not Match
-// a wildcard and the error strategy could not recover from the mismatched
-// symbol
-
-func (p *BaseParser) MatchWildcard() Token {
- t := p.GetCurrentToken()
- if t.GetTokenType() > 0 {
- p.errHandler.ReportMatch(p)
- p.Consume()
- } else {
- t = p.errHandler.RecoverInline(p)
- if p.BuildParseTrees && t.GetTokenIndex() == -1 {
- // we must have conjured up a Newtoken during single token
- // insertion
- // if it's not the current symbol
- p.ctx.AddErrorNode(t)
- }
- }
- return t
-}
-
-func (p *BaseParser) GetParserRuleContext() ParserRuleContext {
- return p.ctx
-}
-
-func (p *BaseParser) SetParserRuleContext(v ParserRuleContext) {
- p.ctx = v
-}
-
-func (p *BaseParser) GetParseListeners() []ParseTreeListener {
- if p.parseListeners == nil {
- return make([]ParseTreeListener, 0)
- }
- return p.parseListeners
-}
-
-// Registers {@code listener} to receive events during the parsing process.
-//
-// To support output-preserving grammar transformations (including but not
-// limited to left-recursion removal, automated left-factoring, and
-// optimized code generation), calls to listener methods during the parse
-// may differ substantially from calls made by
-// {@link ParseTreeWalker//DEFAULT} used after the parse is complete. In
-// particular, rule entry and exit events may occur in a different order
-// during the parse than after the parser. In addition, calls to certain
-// rule entry methods may be omitted.
-//
-// With the following specific exceptions, calls to listener events are
-// deterministic, i.e. for identical input the calls to listener
-// methods will be the same.
-//
-//
-// - Alterations to the grammar used to generate code may change the
-// behavior of the listener calls.
-// - Alterations to the command line options passed to ANTLR 4 when
-// generating the parser may change the behavior of the listener calls.
-// - Changing the version of the ANTLR Tool used to generate the parser
-// may change the behavior of the listener calls.
-//
-//
-// @param listener the listener to add
-//
-// @panics nilPointerException if {@code} listener is {@code nil}
-//
-func (p *BaseParser) AddParseListener(listener ParseTreeListener) {
- if listener == nil {
- panic("listener")
- }
- if p.parseListeners == nil {
- p.parseListeners = make([]ParseTreeListener, 0)
- }
- p.parseListeners = append(p.parseListeners, listener)
-}
-
-//
-// Remove {@code listener} from the list of parse listeners.
-//
-// If {@code listener} is {@code nil} or has not been added as a parse
-// listener, p.method does nothing.
-// @param listener the listener to remove
-//
-func (p *BaseParser) RemoveParseListener(listener ParseTreeListener) {
-
- if p.parseListeners != nil {
-
- idx := -1
- for i, v := range p.parseListeners {
- if v == listener {
- idx = i
- break
- }
- }
-
- if idx == -1 {
- return
- }
-
- // remove the listener from the slice
- p.parseListeners = append(p.parseListeners[0:idx], p.parseListeners[idx+1:]...)
-
- if len(p.parseListeners) == 0 {
- p.parseListeners = nil
- }
- }
-}
-
-// Remove all parse listeners.
-func (p *BaseParser) removeParseListeners() {
- p.parseListeners = nil
-}
-
-// Notify any parse listeners of an enter rule event.
-func (p *BaseParser) TriggerEnterRuleEvent() {
- if p.parseListeners != nil {
- ctx := p.ctx
- for _, listener := range p.parseListeners {
- listener.EnterEveryRule(ctx)
- ctx.EnterRule(listener)
- }
- }
-}
-
-//
-// Notify any parse listeners of an exit rule event.
-//
-// @see //addParseListener
-//
-func (p *BaseParser) TriggerExitRuleEvent() {
- if p.parseListeners != nil {
- // reverse order walk of listeners
- ctx := p.ctx
- l := len(p.parseListeners) - 1
-
- for i := range p.parseListeners {
- listener := p.parseListeners[l-i]
- ctx.ExitRule(listener)
- listener.ExitEveryRule(ctx)
- }
- }
-}
-
-func (p *BaseParser) GetInterpreter() *ParserATNSimulator {
- return p.Interpreter
-}
-
-func (p *BaseParser) GetATN() *ATN {
- return p.Interpreter.atn
-}
-
-func (p *BaseParser) GetTokenFactory() TokenFactory {
- return p.input.GetTokenSource().GetTokenFactory()
-}
-
-// Tell our token source and error strategy about a Newway to create tokens.//
-func (p *BaseParser) setTokenFactory(factory TokenFactory) {
- p.input.GetTokenSource().setTokenFactory(factory)
-}
-
-// The ATN with bypass alternatives is expensive to create so we create it
-// lazily.
-//
-// @panics UnsupportedOperationException if the current parser does not
-// implement the {@link //getSerializedATN()} method.
-//
-func (p *BaseParser) GetATNWithBypassAlts() {
-
- // TODO
- panic("Not implemented!")
-
- // serializedAtn := p.getSerializedATN()
- // if (serializedAtn == nil) {
- // panic("The current parser does not support an ATN with bypass alternatives.")
- // }
- // result := p.bypassAltsAtnCache[serializedAtn]
- // if (result == nil) {
- // deserializationOptions := NewATNDeserializationOptions(nil)
- // deserializationOptions.generateRuleBypassTransitions = true
- // result = NewATNDeserializer(deserializationOptions).deserialize(serializedAtn)
- // p.bypassAltsAtnCache[serializedAtn] = result
- // }
- // return result
-}
-
-// The preferred method of getting a tree pattern. For example, here's a
-// sample use:
-//
-//
-// ParseTree t = parser.expr()
-// ParseTreePattern p = parser.compileParseTreePattern("<ID>+0",
-// MyParser.RULE_expr)
-// ParseTreeMatch m = p.Match(t)
-// String id = m.Get("ID")
-//
-
-func (p *BaseParser) compileParseTreePattern(pattern, patternRuleIndex, lexer Lexer) {
-
- panic("NewParseTreePatternMatcher not implemented!")
- //
- // if (lexer == nil) {
- // if (p.GetTokenStream() != nil) {
- // tokenSource := p.GetTokenStream().GetTokenSource()
- // if _, ok := tokenSource.(ILexer); ok {
- // lexer = tokenSource
- // }
- // }
- // }
- // if (lexer == nil) {
- // panic("Parser can't discover a lexer to use")
- // }
-
- // m := NewParseTreePatternMatcher(lexer, p)
- // return m.compile(pattern, patternRuleIndex)
-}
-
-func (p *BaseParser) GetInputStream() IntStream {
- return p.GetTokenStream()
-}
-
-func (p *BaseParser) SetInputStream(input TokenStream) {
- p.SetTokenStream(input)
-}
-
-func (p *BaseParser) GetTokenStream() TokenStream {
- return p.input
-}
-
-// Set the token stream and reset the parser.//
-func (p *BaseParser) SetTokenStream(input TokenStream) {
- p.input = nil
- p.reset()
- p.input = input
-}
-
-// Match needs to return the current input symbol, which gets put
-// into the label for the associated token ref e.g., x=ID.
-//
-func (p *BaseParser) GetCurrentToken() Token {
- return p.input.LT(1)
-}
-
-func (p *BaseParser) NotifyErrorListeners(msg string, offendingToken Token, err RecognitionException) {
- if offendingToken == nil {
- offendingToken = p.GetCurrentToken()
- }
- p._SyntaxErrors++
- line := offendingToken.GetLine()
- column := offendingToken.GetColumn()
- listener := p.GetErrorListenerDispatch()
- listener.SyntaxError(p, offendingToken, line, column, msg, err)
-}
-
-func (p *BaseParser) Consume() Token {
- o := p.GetCurrentToken()
- if o.GetTokenType() != TokenEOF {
- p.GetInputStream().Consume()
- }
- hasListener := p.parseListeners != nil && len(p.parseListeners) > 0
- if p.BuildParseTrees || hasListener {
- if p.errHandler.inErrorRecoveryMode(p) {
- node := p.ctx.AddErrorNode(o)
- if p.parseListeners != nil {
- for _, l := range p.parseListeners {
- l.VisitErrorNode(node)
- }
- }
-
- } else {
- node := p.ctx.AddTokenNode(o)
- if p.parseListeners != nil {
- for _, l := range p.parseListeners {
- l.VisitTerminal(node)
- }
- }
- }
- // node.invokingState = p.state
- }
-
- return o
-}
-
-func (p *BaseParser) addContextToParseTree() {
- // add current context to parent if we have a parent
- if p.ctx.GetParent() != nil {
- p.ctx.GetParent().(ParserRuleContext).AddChild(p.ctx)
- }
-}
-
-func (p *BaseParser) EnterRule(localctx ParserRuleContext, state, ruleIndex int) {
- p.SetState(state)
- p.ctx = localctx
- p.ctx.SetStart(p.input.LT(1))
- if p.BuildParseTrees {
- p.addContextToParseTree()
- }
- if p.parseListeners != nil {
- p.TriggerEnterRuleEvent()
- }
-}
-
-func (p *BaseParser) ExitRule() {
- p.ctx.SetStop(p.input.LT(-1))
- // trigger event on ctx, before it reverts to parent
- if p.parseListeners != nil {
- p.TriggerExitRuleEvent()
- }
- p.SetState(p.ctx.GetInvokingState())
- if p.ctx.GetParent() != nil {
- p.ctx = p.ctx.GetParent().(ParserRuleContext)
- } else {
- p.ctx = nil
- }
-}
-
-func (p *BaseParser) EnterOuterAlt(localctx ParserRuleContext, altNum int) {
- localctx.SetAltNumber(altNum)
- // if we have Newlocalctx, make sure we replace existing ctx
- // that is previous child of parse tree
- if p.BuildParseTrees && p.ctx != localctx {
- if p.ctx.GetParent() != nil {
- p.ctx.GetParent().(ParserRuleContext).RemoveLastChild()
- p.ctx.GetParent().(ParserRuleContext).AddChild(localctx)
- }
- }
- p.ctx = localctx
-}
-
-// Get the precedence level for the top-most precedence rule.
-//
-// @return The precedence level for the top-most precedence rule, or -1 if
-// the parser context is not nested within a precedence rule.
-
-func (p *BaseParser) GetPrecedence() int {
- if len(p.precedenceStack) == 0 {
- return -1
- }
-
- return p.precedenceStack[len(p.precedenceStack)-1]
-}
-
-func (p *BaseParser) EnterRecursionRule(localctx ParserRuleContext, state, ruleIndex, precedence int) {
- p.SetState(state)
- p.precedenceStack.Push(precedence)
- p.ctx = localctx
- p.ctx.SetStart(p.input.LT(1))
- if p.parseListeners != nil {
- p.TriggerEnterRuleEvent() // simulates rule entry for
- // left-recursive rules
- }
-}
-
-//
-// Like {@link //EnterRule} but for recursive rules.
-
-func (p *BaseParser) PushNewRecursionContext(localctx ParserRuleContext, state, ruleIndex int) {
- previous := p.ctx
- previous.SetParent(localctx)
- previous.SetInvokingState(state)
- previous.SetStop(p.input.LT(-1))
-
- p.ctx = localctx
- p.ctx.SetStart(previous.GetStart())
- if p.BuildParseTrees {
- p.ctx.AddChild(previous)
- }
- if p.parseListeners != nil {
- p.TriggerEnterRuleEvent() // simulates rule entry for
- // left-recursive rules
- }
-}
-
-func (p *BaseParser) UnrollRecursionContexts(parentCtx ParserRuleContext) {
- p.precedenceStack.Pop()
- p.ctx.SetStop(p.input.LT(-1))
- retCtx := p.ctx // save current ctx (return value)
- // unroll so ctx is as it was before call to recursive method
- if p.parseListeners != nil {
- for p.ctx != parentCtx {
- p.TriggerExitRuleEvent()
- p.ctx = p.ctx.GetParent().(ParserRuleContext)
- }
- } else {
- p.ctx = parentCtx
- }
- // hook into tree
- retCtx.SetParent(parentCtx)
- if p.BuildParseTrees && parentCtx != nil {
- // add return ctx into invoking rule's tree
- parentCtx.AddChild(retCtx)
- }
-}
-
-func (p *BaseParser) GetInvokingContext(ruleIndex int) ParserRuleContext {
- ctx := p.ctx
- for ctx != nil {
- if ctx.GetRuleIndex() == ruleIndex {
- return ctx
- }
- ctx = ctx.GetParent().(ParserRuleContext)
- }
- return nil
-}
-
-func (p *BaseParser) Precpred(localctx RuleContext, precedence int) bool {
- return precedence >= p.precedenceStack[len(p.precedenceStack)-1]
-}
-
-func (p *BaseParser) inContext(context ParserRuleContext) bool {
- // TODO: useful in parser?
- return false
-}
-
-//
-// Checks whether or not {@code symbol} can follow the current state in the
-// ATN. The behavior of p.method is equivalent to the following, but is
-// implemented such that the complete context-sensitive follow set does not
-// need to be explicitly constructed.
-//
-//
-// return getExpectedTokens().contains(symbol)
-//
-//
-// @param symbol the symbol type to check
-// @return {@code true} if {@code symbol} can follow the current state in
-// the ATN, otherwise {@code false}.
-
-func (p *BaseParser) IsExpectedToken(symbol int) bool {
- atn := p.Interpreter.atn
- ctx := p.ctx
- s := atn.states[p.state]
- following := atn.NextTokens(s, nil)
- if following.contains(symbol) {
- return true
- }
- if !following.contains(TokenEpsilon) {
- return false
- }
- for ctx != nil && ctx.GetInvokingState() >= 0 && following.contains(TokenEpsilon) {
- invokingState := atn.states[ctx.GetInvokingState()]
- rt := invokingState.GetTransitions()[0]
- following = atn.NextTokens(rt.(*RuleTransition).followState, nil)
- if following.contains(symbol) {
- return true
- }
- ctx = ctx.GetParent().(ParserRuleContext)
- }
- if following.contains(TokenEpsilon) && symbol == TokenEOF {
- return true
- }
-
- return false
-}
-
-// Computes the set of input symbols which could follow the current parser
-// state and context, as given by {@link //GetState} and {@link //GetContext},
-// respectively.
-//
-// @see ATN//getExpectedTokens(int, RuleContext)
-//
-func (p *BaseParser) GetExpectedTokens() *IntervalSet {
- return p.Interpreter.atn.getExpectedTokens(p.state, p.ctx)
-}
-
-func (p *BaseParser) GetExpectedTokensWithinCurrentRule() *IntervalSet {
- atn := p.Interpreter.atn
- s := atn.states[p.state]
- return atn.NextTokens(s, nil)
-}
-
-// Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.//
-func (p *BaseParser) GetRuleIndex(ruleName string) int {
- var ruleIndex, ok = p.GetRuleIndexMap()[ruleName]
- if ok {
- return ruleIndex
- }
-
- return -1
-}
-
-// Return List<String> of the rule names in your parser instance
-// leading up to a call to the current rule. You could override if
-// you want more details such as the file/line info of where
-// in the ATN a rule is invoked.
-//
-// this very useful for error messages.
-
-func (p *BaseParser) GetRuleInvocationStack(c ParserRuleContext) []string {
- if c == nil {
- c = p.ctx
- }
- stack := make([]string, 0)
- for c != nil {
- // compute what follows who invoked us
- ruleIndex := c.GetRuleIndex()
- if ruleIndex < 0 {
- stack = append(stack, "n/a")
- } else {
- stack = append(stack, p.GetRuleNames()[ruleIndex])
- }
-
- vp := c.GetParent()
-
- if vp == nil {
- break
- }
-
- c = vp.(ParserRuleContext)
- }
- return stack
-}
-
-// For debugging and other purposes.//
-func (p *BaseParser) GetDFAStrings() string {
- return fmt.Sprint(p.Interpreter.decisionToDFA)
-}
-
-// For debugging and other purposes.//
-func (p *BaseParser) DumpDFA() {
- seenOne := false
- for _, dfa := range p.Interpreter.decisionToDFA {
- if dfa.numStates() > 0 {
- if seenOne {
- fmt.Println()
- }
- fmt.Println("Decision " + strconv.Itoa(dfa.decision) + ":")
- fmt.Print(dfa.String(p.LiteralNames, p.SymbolicNames))
- seenOne = true
- }
- }
-}
-
-func (p *BaseParser) GetSourceName() string {
- return p.GrammarFileName
-}
-
-// During a parse is sometimes useful to listen in on the rule entry and exit
-// events as well as token Matches. p.is for quick and dirty debugging.
-//
-func (p *BaseParser) SetTrace(trace *TraceListener) {
- if trace == nil {
- p.RemoveParseListener(p.tracer)
- p.tracer = nil
- } else {
- if p.tracer != nil {
- p.RemoveParseListener(p.tracer)
- }
- p.tracer = NewTraceListener(p)
- p.AddParseListener(p.tracer)
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_atn_simulator.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_atn_simulator.go
deleted file mode 100644
index 128b9a9..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_atn_simulator.go
+++ /dev/null
@@ -1,1473 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-var (
- ParserATNSimulatorDebug = false
- ParserATNSimulatorListATNDecisions = false
- ParserATNSimulatorDFADebug = false
- ParserATNSimulatorRetryDebug = false
-)
-
-type ParserATNSimulator struct {
- *BaseATNSimulator
-
- parser Parser
- predictionMode int
- input TokenStream
- startIndex int
- dfa *DFA
- mergeCache *DoubleDict
- outerContext ParserRuleContext
-}
-
-func NewParserATNSimulator(parser Parser, atn *ATN, decisionToDFA []*DFA, sharedContextCache *PredictionContextCache) *ParserATNSimulator {
-
- p := new(ParserATNSimulator)
-
- p.BaseATNSimulator = NewBaseATNSimulator(atn, sharedContextCache)
-
- p.parser = parser
- p.decisionToDFA = decisionToDFA
- // SLL, LL, or LL + exact ambig detection?//
- p.predictionMode = PredictionModeLL
- // LAME globals to avoid parameters!!!!! I need these down deep in predTransition
- p.input = nil
- p.startIndex = 0
- p.outerContext = nil
- p.dfa = nil
- // Each prediction operation uses a cache for merge of prediction contexts.
- // Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
- // isn't Synchronized but we're ok since two threads shouldn't reuse same
- // parser/atnsim object because it can only handle one input at a time.
- // This maps graphs a and b to merged result c. (a,b)&rarrc. We can avoid
- // the merge if we ever see a and b again. Note that (b,a)&rarrc should
- // also be examined during cache lookup.
- //
- p.mergeCache = nil
-
- return p
-}
-
-func (p *ParserATNSimulator) GetPredictionMode() int {
- return p.predictionMode
-}
-
-func (p *ParserATNSimulator) SetPredictionMode(v int) {
- p.predictionMode = v
-}
-
-func (p *ParserATNSimulator) reset() {
-}
-
-func (p *ParserATNSimulator) AdaptivePredict(input TokenStream, decision int, outerContext ParserRuleContext) int {
- if ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
- fmt.Println("AdaptivePredict decision " + strconv.Itoa(decision) +
- " exec LA(1)==" + p.getLookaheadName(input) +
- " line " + strconv.Itoa(input.LT(1).GetLine()) + ":" +
- strconv.Itoa(input.LT(1).GetColumn()))
- }
-
- p.input = input
- p.startIndex = input.Index()
- p.outerContext = outerContext
-
- dfa := p.decisionToDFA[decision]
- p.dfa = dfa
- m := input.Mark()
- index := input.Index()
-
- defer func() {
- p.dfa = nil
- p.mergeCache = nil // wack cache after each prediction
- input.Seek(index)
- input.Release(m)
- }()
-
- // Now we are certain to have a specific decision's DFA
- // But, do we still need an initial state?
- var s0 *DFAState
- if dfa.precedenceDfa {
- // the start state for a precedence DFA depends on the current
- // parser precedence, and is provided by a DFA method.
- s0 = dfa.getPrecedenceStartState(p.parser.GetPrecedence())
- } else {
- // the start state for a "regular" DFA is just s0
- s0 = dfa.s0
- }
-
- if s0 == nil {
- if outerContext == nil {
- outerContext = RuleContextEmpty
- }
- if ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
- fmt.Println("predictATN decision " + strconv.Itoa(dfa.decision) +
- " exec LA(1)==" + p.getLookaheadName(input) +
- ", outerContext=" + outerContext.String(p.parser.GetRuleNames(), nil))
- }
- // If p is not a precedence DFA, we check the ATN start state
- // to determine if p ATN start state is the decision for the
- // closure block that determines whether a precedence rule
- // should continue or complete.
-
- t2 := dfa.atnStartState
- t, ok := t2.(*StarLoopEntryState)
- if !dfa.precedenceDfa && ok {
- if t.precedenceRuleDecision {
- dfa.setPrecedenceDfa(true)
- }
- }
- fullCtx := false
- s0Closure := p.computeStartState(dfa.atnStartState, RuleContextEmpty, fullCtx)
-
- if dfa.precedenceDfa {
- // If p is a precedence DFA, we use applyPrecedenceFilter
- // to convert the computed start state to a precedence start
- // state. We then use DFA.setPrecedenceStartState to set the
- // appropriate start state for the precedence level rather
- // than simply setting DFA.s0.
- //
- s0Closure = p.applyPrecedenceFilter(s0Closure)
- s0 = p.addDFAState(dfa, NewDFAState(-1, s0Closure))
- dfa.setPrecedenceStartState(p.parser.GetPrecedence(), s0)
- } else {
- s0 = p.addDFAState(dfa, NewDFAState(-1, s0Closure))
- dfa.s0 = s0
- }
- }
- alt := p.execATN(dfa, s0, input, index, outerContext)
- if ParserATNSimulatorDebug {
- fmt.Println("DFA after predictATN: " + dfa.String(p.parser.GetLiteralNames(), nil))
- }
- return alt
-
-}
-
-// Performs ATN simulation to compute a predicted alternative based
-// upon the remaining input, but also updates the DFA cache to avoid
-// having to traverse the ATN again for the same input sequence.
-
-// There are some key conditions we're looking for after computing a new
-// set of ATN configs (proposed DFA state):
-// if the set is empty, there is no viable alternative for current symbol
-// does the state uniquely predict an alternative?
-// does the state have a conflict that would prevent us from
-// putting it on the work list?
-
-// We also have some key operations to do:
-// add an edge from previous DFA state to potentially NewDFA state, D,
-// upon current symbol but only if adding to work list, which means in all
-// cases except no viable alternative (and possibly non-greedy decisions?)
-// collecting predicates and adding semantic context to DFA accept states
-// adding rule context to context-sensitive DFA accept states
-// consuming an input symbol
-// Reporting a conflict
-// Reporting an ambiguity
-// Reporting a context sensitivity
-// Reporting insufficient predicates
-
-// cover these cases:
-// dead end
-// single alt
-// single alt + preds
-// conflict
-// conflict + preds
-//
-func (p *ParserATNSimulator) execATN(dfa *DFA, s0 *DFAState, input TokenStream, startIndex int, outerContext ParserRuleContext) int {
-
- if ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
- fmt.Println("execATN decision " + strconv.Itoa(dfa.decision) +
- " exec LA(1)==" + p.getLookaheadName(input) +
- " line " + strconv.Itoa(input.LT(1).GetLine()) + ":" + strconv.Itoa(input.LT(1).GetColumn()))
- }
-
- previousD := s0
-
- if ParserATNSimulatorDebug {
- fmt.Println("s0 = " + s0.String())
- }
- t := input.LA(1)
- for { // for more work
- D := p.getExistingTargetState(previousD, t)
- if D == nil {
- D = p.computeTargetState(dfa, previousD, t)
- }
- if D == ATNSimulatorError {
- // if any configs in previous dipped into outer context, that
- // means that input up to t actually finished entry rule
- // at least for SLL decision. Full LL doesn't dip into outer
- // so don't need special case.
- // We will get an error no matter what so delay until after
- // decision better error message. Also, no reachable target
- // ATN states in SLL implies LL will also get nowhere.
- // If conflict in states that dip out, choose min since we
- // will get error no matter what.
- e := p.noViableAlt(input, outerContext, previousD.configs, startIndex)
- input.Seek(startIndex)
- alt := p.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext)
- if alt != ATNInvalidAltNumber {
- return alt
- }
-
- panic(e)
- }
- if D.requiresFullContext && p.predictionMode != PredictionModeSLL {
- // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
- conflictingAlts := D.configs.GetConflictingAlts()
- if D.predicates != nil {
- if ParserATNSimulatorDebug {
- fmt.Println("DFA state has preds in DFA sim LL failover")
- }
- conflictIndex := input.Index()
- if conflictIndex != startIndex {
- input.Seek(startIndex)
- }
- conflictingAlts = p.evalSemanticContext(D.predicates, outerContext, true)
- if conflictingAlts.length() == 1 {
- if ParserATNSimulatorDebug {
- fmt.Println("Full LL avoided")
- }
- return conflictingAlts.minValue()
- }
- if conflictIndex != startIndex {
- // restore the index so Reporting the fallback to full
- // context occurs with the index at the correct spot
- input.Seek(conflictIndex)
- }
- }
- if ParserATNSimulatorDFADebug {
- fmt.Println("ctx sensitive state " + outerContext.String(nil, nil) + " in " + D.String())
- }
- fullCtx := true
- s0Closure := p.computeStartState(dfa.atnStartState, outerContext, fullCtx)
- p.ReportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.Index())
- alt := p.execATNWithFullContext(dfa, D, s0Closure, input, startIndex, outerContext)
- return alt
- }
- if D.isAcceptState {
- if D.predicates == nil {
- return D.prediction
- }
- stopIndex := input.Index()
- input.Seek(startIndex)
- alts := p.evalSemanticContext(D.predicates, outerContext, true)
- if alts.length() == 0 {
- panic(p.noViableAlt(input, outerContext, D.configs, startIndex))
- } else if alts.length() == 1 {
- return alts.minValue()
- } else {
- // Report ambiguity after predicate evaluation to make sure the correct set of ambig alts is Reported.
- p.ReportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs)
- return alts.minValue()
- }
- }
- previousD = D
-
- if t != TokenEOF {
- input.Consume()
- t = input.LA(1)
- }
- }
-
- panic("Should not have reached p state")
-}
-
-// Get an existing target state for an edge in the DFA. If the target state
-// for the edge has not yet been computed or is otherwise not available,
-// p method returns {@code nil}.
-//
-// @param previousD The current DFA state
-// @param t The next input symbol
-// @return The existing target DFA state for the given input symbol
-// {@code t}, or {@code nil} if the target state for p edge is not
-// already cached
-
-func (p *ParserATNSimulator) getExistingTargetState(previousD *DFAState, t int) *DFAState {
- edges := previousD.edges
- if edges == nil {
- return nil
- }
-
- return edges[t+1]
-}
-
-// Compute a target state for an edge in the DFA, and attempt to add the
-// computed state and corresponding edge to the DFA.
-//
-// @param dfa The DFA
-// @param previousD The current DFA state
-// @param t The next input symbol
-//
-// @return The computed target DFA state for the given input symbol
-// {@code t}. If {@code t} does not lead to a valid DFA state, p method
-// returns {@link //ERROR}.
-
-func (p *ParserATNSimulator) computeTargetState(dfa *DFA, previousD *DFAState, t int) *DFAState {
- reach := p.computeReachSet(previousD.configs, t, false)
-
- if reach == nil {
- p.addDFAEdge(dfa, previousD, t, ATNSimulatorError)
- return ATNSimulatorError
- }
- // create Newtarget state we'll add to DFA after it's complete
- D := NewDFAState(-1, reach)
-
- predictedAlt := p.getUniqueAlt(reach)
-
- if ParserATNSimulatorDebug {
- altSubSets := PredictionModegetConflictingAltSubsets(reach)
- fmt.Println("SLL altSubSets=" + fmt.Sprint(altSubSets) +
- ", previous=" + previousD.configs.String() +
- ", configs=" + reach.String() +
- ", predict=" + strconv.Itoa(predictedAlt) +
- ", allSubsetsConflict=" +
- fmt.Sprint(PredictionModeallSubsetsConflict(altSubSets)) +
- ", conflictingAlts=" + p.getConflictingAlts(reach).String())
- }
- if predictedAlt != ATNInvalidAltNumber {
- // NO CONFLICT, UNIQUELY PREDICTED ALT
- D.isAcceptState = true
- D.configs.SetUniqueAlt(predictedAlt)
- D.setPrediction(predictedAlt)
- } else if PredictionModehasSLLConflictTerminatingPrediction(p.predictionMode, reach) {
- // MORE THAN ONE VIABLE ALTERNATIVE
- D.configs.SetConflictingAlts(p.getConflictingAlts(reach))
- D.requiresFullContext = true
- // in SLL-only mode, we will stop at p state and return the minimum alt
- D.isAcceptState = true
- D.setPrediction(D.configs.GetConflictingAlts().minValue())
- }
- if D.isAcceptState && D.configs.HasSemanticContext() {
- p.predicateDFAState(D, p.atn.getDecisionState(dfa.decision))
- if D.predicates != nil {
- D.setPrediction(ATNInvalidAltNumber)
- }
- }
- // all adds to dfa are done after we've created full D state
- D = p.addDFAEdge(dfa, previousD, t, D)
- return D
-}
-
-func (p *ParserATNSimulator) predicateDFAState(dfaState *DFAState, decisionState DecisionState) {
- // We need to test all predicates, even in DFA states that
- // uniquely predict alternative.
- nalts := len(decisionState.GetTransitions())
- // Update DFA so reach becomes accept state with (predicate,alt)
- // pairs if preds found for conflicting alts
- altsToCollectPredsFrom := p.getConflictingAltsOrUniqueAlt(dfaState.configs)
- altToPred := p.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts)
- if altToPred != nil {
- dfaState.predicates = p.getPredicatePredictions(altsToCollectPredsFrom, altToPred)
- dfaState.setPrediction(ATNInvalidAltNumber) // make sure we use preds
- } else {
- // There are preds in configs but they might go away
- // when OR'd together like {p}? || NONE == NONE. If neither
- // alt has preds, resolve to min alt
- dfaState.setPrediction(altsToCollectPredsFrom.minValue())
- }
-}
-
-// comes back with reach.uniqueAlt set to a valid alt
-func (p *ParserATNSimulator) execATNWithFullContext(dfa *DFA, D *DFAState, s0 ATNConfigSet, input TokenStream, startIndex int, outerContext ParserRuleContext) int {
-
- if ParserATNSimulatorDebug || ParserATNSimulatorListATNDecisions {
- fmt.Println("execATNWithFullContext " + s0.String())
- }
-
- fullCtx := true
- foundExactAmbig := false
- var reach ATNConfigSet
- previous := s0
- input.Seek(startIndex)
- t := input.LA(1)
- predictedAlt := -1
-
- for { // for more work
- reach = p.computeReachSet(previous, t, fullCtx)
- if reach == nil {
- // if any configs in previous dipped into outer context, that
- // means that input up to t actually finished entry rule
- // at least for LL decision. Full LL doesn't dip into outer
- // so don't need special case.
- // We will get an error no matter what so delay until after
- // decision better error message. Also, no reachable target
- // ATN states in SLL implies LL will also get nowhere.
- // If conflict in states that dip out, choose min since we
- // will get error no matter what.
- e := p.noViableAlt(input, outerContext, previous, startIndex)
- input.Seek(startIndex)
- alt := p.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext)
- if alt != ATNInvalidAltNumber {
- return alt
- }
-
- panic(e)
- }
- altSubSets := PredictionModegetConflictingAltSubsets(reach)
- if ParserATNSimulatorDebug {
- fmt.Println("LL altSubSets=" + fmt.Sprint(altSubSets) + ", predict=" +
- strconv.Itoa(PredictionModegetUniqueAlt(altSubSets)) + ", resolvesToJustOneViableAlt=" +
- fmt.Sprint(PredictionModeresolvesToJustOneViableAlt(altSubSets)))
- }
- reach.SetUniqueAlt(p.getUniqueAlt(reach))
- // unique prediction?
- if reach.GetUniqueAlt() != ATNInvalidAltNumber {
- predictedAlt = reach.GetUniqueAlt()
- break
- } else if p.predictionMode != PredictionModeLLExactAmbigDetection {
- predictedAlt = PredictionModeresolvesToJustOneViableAlt(altSubSets)
- if predictedAlt != ATNInvalidAltNumber {
- break
- }
- } else {
- // In exact ambiguity mode, we never try to terminate early.
- // Just keeps scarfing until we know what the conflict is
- if PredictionModeallSubsetsConflict(altSubSets) && PredictionModeallSubsetsEqual(altSubSets) {
- foundExactAmbig = true
- predictedAlt = PredictionModegetSingleViableAlt(altSubSets)
- break
- }
- // else there are multiple non-conflicting subsets or
- // we're not sure what the ambiguity is yet.
- // So, keep going.
- }
- previous = reach
- if t != TokenEOF {
- input.Consume()
- t = input.LA(1)
- }
- }
- // If the configuration set uniquely predicts an alternative,
- // without conflict, then we know that it's a full LL decision
- // not SLL.
- if reach.GetUniqueAlt() != ATNInvalidAltNumber {
- p.ReportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.Index())
- return predictedAlt
- }
- // We do not check predicates here because we have checked them
- // on-the-fly when doing full context prediction.
-
- //
- // In non-exact ambiguity detection mode, we might actually be able to
- // detect an exact ambiguity, but I'm not going to spend the cycles
- // needed to check. We only emit ambiguity warnings in exact ambiguity
- // mode.
- //
- // For example, we might know that we have conflicting configurations.
- // But, that does not mean that there is no way forward without a
- // conflict. It's possible to have nonconflicting alt subsets as in:
-
- // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]
-
- // from
- //
- // [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
- // (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
- //
- // In p case, (17,1,[5 $]) indicates there is some next sequence that
- // would resolve p without conflict to alternative 1. Any other viable
- // next sequence, however, is associated with a conflict. We stop
- // looking for input because no amount of further lookahead will alter
- // the fact that we should predict alternative 1. We just can't say for
- // sure that there is an ambiguity without looking further.
-
- p.ReportAmbiguity(dfa, D, startIndex, input.Index(), foundExactAmbig, nil, reach)
-
- return predictedAlt
-}
-
-func (p *ParserATNSimulator) computeReachSet(closure ATNConfigSet, t int, fullCtx bool) ATNConfigSet {
- if ParserATNSimulatorDebug {
- fmt.Println("in computeReachSet, starting closure: " + closure.String())
- }
- if p.mergeCache == nil {
- p.mergeCache = NewDoubleDict()
- }
- intermediate := NewBaseATNConfigSet(fullCtx)
-
- // Configurations already in a rule stop state indicate reaching the end
- // of the decision rule (local context) or end of the start rule (full
- // context). Once reached, these configurations are never updated by a
- // closure operation, so they are handled separately for the performance
- // advantage of having a smaller intermediate set when calling closure.
- //
- // For full-context reach operations, separate handling is required to
- // ensure that the alternative Matching the longest overall sequence is
- // chosen when multiple such configurations can Match the input.
-
- var SkippedStopStates []*BaseATNConfig
-
- // First figure out where we can reach on input t
- for _, c := range closure.GetItems() {
- if ParserATNSimulatorDebug {
- fmt.Println("testing " + p.GetTokenName(t) + " at " + c.String())
- }
-
- _, ok := c.GetState().(*RuleStopState)
-
- if ok {
- if fullCtx || t == TokenEOF {
- if SkippedStopStates == nil {
- SkippedStopStates = make([]*BaseATNConfig, 0)
- }
- SkippedStopStates = append(SkippedStopStates, c.(*BaseATNConfig))
- if ParserATNSimulatorDebug {
- fmt.Println("added " + c.String() + " to SkippedStopStates")
- }
- }
- continue
- }
-
- for j := 0; j < len(c.GetState().GetTransitions()); j++ {
- trans := c.GetState().GetTransitions()[j]
- target := p.getReachableTarget(trans, t)
- if target != nil {
- cfg := NewBaseATNConfig4(c, target)
- intermediate.Add(cfg, p.mergeCache)
- if ParserATNSimulatorDebug {
- fmt.Println("added " + cfg.String() + " to intermediate")
- }
- }
- }
- }
- // Now figure out where the reach operation can take us...
- var reach ATNConfigSet
-
- // This block optimizes the reach operation for intermediate sets which
- // trivially indicate a termination state for the overall
- // AdaptivePredict operation.
- //
- // The conditions assume that intermediate
- // contains all configurations relevant to the reach set, but p
- // condition is not true when one or more configurations have been
- // withheld in SkippedStopStates, or when the current symbol is EOF.
- //
- if SkippedStopStates == nil && t != TokenEOF {
- if len(intermediate.configs) == 1 {
- // Don't pursue the closure if there is just one state.
- // It can only have one alternative just add to result
- // Also don't pursue the closure if there is unique alternative
- // among the configurations.
- reach = intermediate
- } else if p.getUniqueAlt(intermediate) != ATNInvalidAltNumber {
- // Also don't pursue the closure if there is unique alternative
- // among the configurations.
- reach = intermediate
- }
- }
- // If the reach set could not be trivially determined, perform a closure
- // operation on the intermediate set to compute its initial value.
- //
- if reach == nil {
- reach = NewBaseATNConfigSet(fullCtx)
- closureBusy := NewSet(nil, nil)
- treatEOFAsEpsilon := t == TokenEOF
- for k := 0; k < len(intermediate.configs); k++ {
- p.closure(intermediate.configs[k], reach, closureBusy, false, fullCtx, treatEOFAsEpsilon)
- }
- }
- if t == TokenEOF {
- // After consuming EOF no additional input is possible, so we are
- // only interested in configurations which reached the end of the
- // decision rule (local context) or end of the start rule (full
- // context). Update reach to contain only these configurations. This
- // handles both explicit EOF transitions in the grammar and implicit
- // EOF transitions following the end of the decision or start rule.
- //
- // When reach==intermediate, no closure operation was performed. In
- // p case, removeAllConfigsNotInRuleStopState needs to check for
- // reachable rule stop states as well as configurations already in
- // a rule stop state.
- //
- // This is handled before the configurations in SkippedStopStates,
- // because any configurations potentially added from that list are
- // already guaranteed to meet p condition whether or not it's
- // required.
- //
- reach = p.removeAllConfigsNotInRuleStopState(reach, reach == intermediate)
- }
- // If SkippedStopStates!=nil, then it contains at least one
- // configuration. For full-context reach operations, these
- // configurations reached the end of the start rule, in which case we
- // only add them back to reach if no configuration during the current
- // closure operation reached such a state. This ensures AdaptivePredict
- // chooses an alternative Matching the longest overall sequence when
- // multiple alternatives are viable.
- //
- if SkippedStopStates != nil && ((!fullCtx) || (!PredictionModehasConfigInRuleStopState(reach))) {
- for l := 0; l < len(SkippedStopStates); l++ {
- reach.Add(SkippedStopStates[l], p.mergeCache)
- }
- }
- if len(reach.GetItems()) == 0 {
- return nil
- }
-
- return reach
-}
-
-//
-// Return a configuration set containing only the configurations from
-// {@code configs} which are in a {@link RuleStopState}. If all
-// configurations in {@code configs} are already in a rule stop state, p
-// method simply returns {@code configs}.
-//
-// When {@code lookToEndOfRule} is true, p method uses
-// {@link ATN//NextTokens} for each configuration in {@code configs} which is
-// not already in a rule stop state to see if a rule stop state is reachable
-// from the configuration via epsilon-only transitions.
-//
-// @param configs the configuration set to update
-// @param lookToEndOfRule when true, p method checks for rule stop states
-// reachable by epsilon-only transitions from each configuration in
-// {@code configs}.
-//
-// @return {@code configs} if all configurations in {@code configs} are in a
-// rule stop state, otherwise return a Newconfiguration set containing only
-// the configurations from {@code configs} which are in a rule stop state
-//
-func (p *ParserATNSimulator) removeAllConfigsNotInRuleStopState(configs ATNConfigSet, lookToEndOfRule bool) ATNConfigSet {
- if PredictionModeallConfigsInRuleStopStates(configs) {
- return configs
- }
- result := NewBaseATNConfigSet(configs.FullContext())
- for _, config := range configs.GetItems() {
-
- _, ok := config.GetState().(*RuleStopState)
-
- if ok {
- result.Add(config, p.mergeCache)
- continue
- }
- if lookToEndOfRule && config.GetState().GetEpsilonOnlyTransitions() {
- NextTokens := p.atn.NextTokens(config.GetState(), nil)
- if NextTokens.contains(TokenEpsilon) {
- endOfRuleState := p.atn.ruleToStopState[config.GetState().GetRuleIndex()]
- result.Add(NewBaseATNConfig4(config, endOfRuleState), p.mergeCache)
- }
- }
- }
- return result
-}
-
-func (p *ParserATNSimulator) computeStartState(a ATNState, ctx RuleContext, fullCtx bool) ATNConfigSet {
- // always at least the implicit call to start rule
- initialContext := predictionContextFromRuleContext(p.atn, ctx)
- configs := NewBaseATNConfigSet(fullCtx)
- for i := 0; i < len(a.GetTransitions()); i++ {
- target := a.GetTransitions()[i].getTarget()
- c := NewBaseATNConfig6(target, i+1, initialContext)
- closureBusy := NewSet(nil, nil)
- p.closure(c, configs, closureBusy, true, fullCtx, false)
- }
- return configs
-}
-
-//
-// This method transforms the start state computed by
-// {@link //computeStartState} to the special start state used by a
-// precedence DFA for a particular precedence value. The transformation
-// process applies the following changes to the start state's configuration
-// set.
-//
-//
-// - Evaluate the precedence predicates for each configuration using
-// {@link SemanticContext//evalPrecedence}.
-// - Remove all configurations which predict an alternative greater than
-// 1, for which another configuration that predicts alternative 1 is in the
-// same ATN state with the same prediction context. This transformation is
-// valid for the following reasons:
-//
-// - The closure block cannot contain any epsilon transitions which bypass
-// the body of the closure, so all states reachable via alternative 1 are
-// part of the precedence alternatives of the transformed left-recursive
-// rule.
-// - The "primary" portion of a left recursive rule cannot contain an
-// epsilon transition, so the only way an alternative other than 1 can exist
-// in a state that is also reachable via alternative 1 is by nesting calls
-// to the left-recursive rule, with the outer calls not being at the
-// preferred precedence level.
-//
-//
-//
-//
-//
-// The prediction context must be considered by p filter to address
-// situations like the following.
-//
-//
-//
-// grammar TA
-// prog: statement* EOF
-// statement: letterA | statement letterA 'b'
-// letterA: 'a'
-//
-//
-//
-// If the above grammar, the ATN state immediately before the token
-// reference {@code 'a'} in {@code letterA} is reachable from the left edge
-// of both the primary and closure blocks of the left-recursive rule
-// {@code statement}. The prediction context associated with each of these
-// configurations distinguishes between them, and prevents the alternative
-// which stepped out to {@code prog} (and then back in to {@code statement}
-// from being eliminated by the filter.
-//
-//
-// @param configs The configuration set computed by
-// {@link //computeStartState} as the start state for the DFA.
-// @return The transformed configuration set representing the start state
-// for a precedence DFA at a particular precedence level (determined by
-// calling {@link Parser//getPrecedence}).
-//
-func (p *ParserATNSimulator) applyPrecedenceFilter(configs ATNConfigSet) ATNConfigSet {
-
- statesFromAlt1 := make(map[int]PredictionContext)
- configSet := NewBaseATNConfigSet(configs.FullContext())
-
- for _, config := range configs.GetItems() {
- // handle alt 1 first
- if config.GetAlt() != 1 {
- continue
- }
- updatedContext := config.GetSemanticContext().evalPrecedence(p.parser, p.outerContext)
- if updatedContext == nil {
- // the configuration was eliminated
- continue
- }
- statesFromAlt1[config.GetState().GetStateNumber()] = config.GetContext()
- if updatedContext != config.GetSemanticContext() {
- configSet.Add(NewBaseATNConfig2(config, updatedContext), p.mergeCache)
- } else {
- configSet.Add(config, p.mergeCache)
- }
- }
- for _, config := range configs.GetItems() {
-
- if config.GetAlt() == 1 {
- // already handled
- continue
- }
- // In the future, p elimination step could be updated to also
- // filter the prediction context for alternatives predicting alt>1
- // (basically a graph subtraction algorithm).
- if !config.getPrecedenceFilterSuppressed() {
- context := statesFromAlt1[config.GetState().GetStateNumber()]
- if context != nil && context.equals(config.GetContext()) {
- // eliminated
- continue
- }
- }
- configSet.Add(config, p.mergeCache)
- }
- return configSet
-}
-
-func (p *ParserATNSimulator) getReachableTarget(trans Transition, ttype int) ATNState {
- if trans.Matches(ttype, 0, p.atn.maxTokenType) {
- return trans.getTarget()
- }
-
- return nil
-}
-
-func (p *ParserATNSimulator) getPredsForAmbigAlts(ambigAlts *BitSet, configs ATNConfigSet, nalts int) []SemanticContext {
-
- altToPred := make([]SemanticContext, nalts+1)
- for _, c := range configs.GetItems() {
- if ambigAlts.contains(c.GetAlt()) {
- altToPred[c.GetAlt()] = SemanticContextorContext(altToPred[c.GetAlt()], c.GetSemanticContext())
- }
- }
- nPredAlts := 0
- for i := 1; i < nalts+1; i++ {
- pred := altToPred[i]
- if pred == nil {
- altToPred[i] = SemanticContextNone
- } else if pred != SemanticContextNone {
- nPredAlts++
- }
- }
- // nonambig alts are nil in altToPred
- if nPredAlts == 0 {
- altToPred = nil
- }
- if ParserATNSimulatorDebug {
- fmt.Println("getPredsForAmbigAlts result " + fmt.Sprint(altToPred))
- }
- return altToPred
-}
-
-func (p *ParserATNSimulator) getPredicatePredictions(ambigAlts *BitSet, altToPred []SemanticContext) []*PredPrediction {
- pairs := make([]*PredPrediction, 0)
- containsPredicate := false
- for i := 1; i < len(altToPred); i++ {
- pred := altToPred[i]
- // unpredicated is indicated by SemanticContextNONE
- if ambigAlts != nil && ambigAlts.contains(i) {
- pairs = append(pairs, NewPredPrediction(pred, i))
- }
- if pred != SemanticContextNone {
- containsPredicate = true
- }
- }
- if !containsPredicate {
- return nil
- }
- return pairs
-}
-
-//
-// This method is used to improve the localization of error messages by
-// choosing an alternative rather than panicing a
-// {@link NoViableAltException} in particular prediction scenarios where the
-// {@link //ERROR} state was reached during ATN simulation.
-//
-//
-// The default implementation of p method uses the following
-// algorithm to identify an ATN configuration which successfully parsed the
-// decision entry rule. Choosing such an alternative ensures that the
-// {@link ParserRuleContext} returned by the calling rule will be complete
-// and valid, and the syntax error will be Reported later at a more
-// localized location.
-//
-//
-// - If a syntactically valid path or paths reach the end of the decision rule and
-// they are semantically valid if predicated, return the min associated alt.
-// - Else, if a semantically invalid but syntactically valid path exist
-// or paths exist, return the minimum associated alt.
-//
-// - Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.
-//
-//
-//
-// In some scenarios, the algorithm described above could predict an
-// alternative which will result in a {@link FailedPredicateException} in
-// the parser. Specifically, p could occur if the only configuration
-// capable of successfully parsing to the end of the decision rule is
-// blocked by a semantic predicate. By choosing p alternative within
-// {@link //AdaptivePredict} instead of panicing a
-// {@link NoViableAltException}, the resulting
-// {@link FailedPredicateException} in the parser will identify the specific
-// predicate which is preventing the parser from successfully parsing the
-// decision rule, which helps developers identify and correct logic errors
-// in semantic predicates.
-//
-//
-// @param configs The ATN configurations which were valid immediately before
-// the {@link //ERROR} state was reached
-// @param outerContext The is the \gamma_0 initial parser context from the paper
-// or the parser stack at the instant before prediction commences.
-//
-// @return The value to return from {@link //AdaptivePredict}, or
-// {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
-// identified and {@link //AdaptivePredict} should Report an error instead.
-//
-func (p *ParserATNSimulator) getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(configs ATNConfigSet, outerContext ParserRuleContext) int {
- cfgs := p.splitAccordingToSemanticValidity(configs, outerContext)
- semValidConfigs := cfgs[0]
- semInvalidConfigs := cfgs[1]
- alt := p.GetAltThatFinishedDecisionEntryRule(semValidConfigs)
- if alt != ATNInvalidAltNumber { // semantically/syntactically viable path exists
- return alt
- }
- // Is there a syntactically valid path with a failed pred?
- if len(semInvalidConfigs.GetItems()) > 0 {
- alt = p.GetAltThatFinishedDecisionEntryRule(semInvalidConfigs)
- if alt != ATNInvalidAltNumber { // syntactically viable path exists
- return alt
- }
- }
- return ATNInvalidAltNumber
-}
-
-func (p *ParserATNSimulator) GetAltThatFinishedDecisionEntryRule(configs ATNConfigSet) int {
- alts := NewIntervalSet()
-
- for _, c := range configs.GetItems() {
- _, ok := c.GetState().(*RuleStopState)
-
- if c.GetReachesIntoOuterContext() > 0 || (ok && c.GetContext().hasEmptyPath()) {
- alts.addOne(c.GetAlt())
- }
- }
- if alts.length() == 0 {
- return ATNInvalidAltNumber
- }
-
- return alts.first()
-}
-
-// Walk the list of configurations and split them according to
-// those that have preds evaluating to true/false. If no pred, assume
-// true pred and include in succeeded set. Returns Pair of sets.
-//
-// Create a NewSet so as not to alter the incoming parameter.
-//
-// Assumption: the input stream has been restored to the starting point
-// prediction, which is where predicates need to evaluate.
-
-type ATNConfigSetPair struct {
- item0, item1 ATNConfigSet
-}
-
-func (p *ParserATNSimulator) splitAccordingToSemanticValidity(configs ATNConfigSet, outerContext ParserRuleContext) []ATNConfigSet {
- succeeded := NewBaseATNConfigSet(configs.FullContext())
- failed := NewBaseATNConfigSet(configs.FullContext())
-
- for _, c := range configs.GetItems() {
- if c.GetSemanticContext() != SemanticContextNone {
- predicateEvaluationResult := c.GetSemanticContext().evaluate(p.parser, outerContext)
- if predicateEvaluationResult {
- succeeded.Add(c, nil)
- } else {
- failed.Add(c, nil)
- }
- } else {
- succeeded.Add(c, nil)
- }
- }
- return []ATNConfigSet{succeeded, failed}
-}
-
-// Look through a list of predicate/alt pairs, returning alts for the
-// pairs that win. A {@code NONE} predicate indicates an alt containing an
-// unpredicated config which behaves as "always true." If !complete
-// then we stop at the first predicate that evaluates to true. This
-// includes pairs with nil predicates.
-//
-func (p *ParserATNSimulator) evalSemanticContext(predPredictions []*PredPrediction, outerContext ParserRuleContext, complete bool) *BitSet {
- predictions := NewBitSet()
- for i := 0; i < len(predPredictions); i++ {
- pair := predPredictions[i]
- if pair.pred == SemanticContextNone {
- predictions.add(pair.alt)
- if !complete {
- break
- }
- continue
- }
-
- predicateEvaluationResult := pair.pred.evaluate(p.parser, outerContext)
- if ParserATNSimulatorDebug || ParserATNSimulatorDFADebug {
- fmt.Println("eval pred " + pair.String() + "=" + fmt.Sprint(predicateEvaluationResult))
- }
- if predicateEvaluationResult {
- if ParserATNSimulatorDebug || ParserATNSimulatorDFADebug {
- fmt.Println("PREDICT " + fmt.Sprint(pair.alt))
- }
- predictions.add(pair.alt)
- if !complete {
- break
- }
- }
- }
- return predictions
-}
-
-func (p *ParserATNSimulator) closure(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx, treatEOFAsEpsilon bool) {
- initialDepth := 0
- p.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
- fullCtx, initialDepth, treatEOFAsEpsilon)
-}
-
-func (p *ParserATNSimulator) closureCheckingStopState(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEOFAsEpsilon bool) {
-
- if ParserATNSimulatorDebug {
- fmt.Println("closure(" + config.String() + ")")
- fmt.Println("configs(" + configs.String() + ")")
- if config.GetReachesIntoOuterContext() > 50 {
- panic("problem")
- }
- }
-
- _, ok := config.GetState().(*RuleStopState)
- if ok {
- // We hit rule end. If we have context info, use it
- // run thru all possible stack tops in ctx
- if !config.GetContext().isEmpty() {
- for i := 0; i < config.GetContext().length(); i++ {
- if config.GetContext().getReturnState(i) == BasePredictionContextEmptyReturnState {
- if fullCtx {
- configs.Add(NewBaseATNConfig1(config, config.GetState(), BasePredictionContextEMPTY), p.mergeCache)
- continue
- } else {
- // we have no context info, just chase follow links (if greedy)
- if ParserATNSimulatorDebug {
- fmt.Println("FALLING off rule " + p.getRuleName(config.GetState().GetRuleIndex()))
- }
- p.closureWork(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)
- }
- continue
- }
- returnState := p.atn.states[config.GetContext().getReturnState(i)]
- newContext := config.GetContext().GetParent(i) // "pop" return state
-
- c := NewBaseATNConfig5(returnState, config.GetAlt(), newContext, config.GetSemanticContext())
- // While we have context to pop back from, we may have
- // gotten that context AFTER having falling off a rule.
- // Make sure we track that we are now out of context.
- c.SetReachesIntoOuterContext(config.GetReachesIntoOuterContext())
- p.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth-1, treatEOFAsEpsilon)
- }
- return
- } else if fullCtx {
- // reached end of start rule
- configs.Add(config, p.mergeCache)
- return
- } else {
- // else if we have no context info, just chase follow links (if greedy)
- if ParserATNSimulatorDebug {
- fmt.Println("FALLING off rule " + p.getRuleName(config.GetState().GetRuleIndex()))
- }
- }
- }
- p.closureWork(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEOFAsEpsilon)
-}
-
-// Do the actual work of walking epsilon edges//
-func (p *ParserATNSimulator) closureWork(config ATNConfig, configs ATNConfigSet, closureBusy *Set, collectPredicates, fullCtx bool, depth int, treatEOFAsEpsilon bool) {
- state := config.GetState()
- // optimization
- if !state.GetEpsilonOnlyTransitions() {
- configs.Add(config, p.mergeCache)
- // make sure to not return here, because EOF transitions can act as
- // both epsilon transitions and non-epsilon transitions.
- }
- for i := 0; i < len(state.GetTransitions()); i++ {
- t := state.GetTransitions()[i]
- _, ok := t.(*ActionTransition)
- continueCollecting := collectPredicates && !ok
- c := p.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEOFAsEpsilon)
- if ci, ok := c.(*BaseATNConfig); ok && ci != nil {
- if !t.getIsEpsilon() && closureBusy.add(c) != c {
- // avoid infinite recursion for EOF* and EOF+
- continue
- }
- newDepth := depth
-
- if _, ok := config.GetState().(*RuleStopState); ok {
-
- // target fell off end of rule mark resulting c as having dipped into outer context
- // We can't get here if incoming config was rule stop and we had context
- // track how far we dip into outer context. Might
- // come in handy and we avoid evaluating context dependent
- // preds if p is > 0.
-
- if closureBusy.add(c) != c {
- // avoid infinite recursion for right-recursive rules
- continue
- }
-
- if p.dfa != nil && p.dfa.precedenceDfa {
- if t.(*EpsilonTransition).outermostPrecedenceReturn == p.dfa.atnStartState.GetRuleIndex() {
- c.setPrecedenceFilterSuppressed(true)
- }
- }
-
- c.SetReachesIntoOuterContext(c.GetReachesIntoOuterContext() + 1)
- configs.SetDipsIntoOuterContext(true) // TODO: can remove? only care when we add to set per middle of p method
- newDepth--
- if ParserATNSimulatorDebug {
- fmt.Println("dips into outer ctx: " + c.String())
- }
- } else if _, ok := t.(*RuleTransition); ok {
- // latch when newDepth goes negative - once we step out of the entry context we can't return
- if newDepth >= 0 {
- newDepth++
- }
- }
- p.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEOFAsEpsilon)
- }
- }
-}
-
-func (p *ParserATNSimulator) getRuleName(index int) string {
- if p.parser != nil && index >= 0 {
- return p.parser.GetRuleNames()[index]
- }
-
- return ""
-}
-
-func (p *ParserATNSimulator) getEpsilonTarget(config ATNConfig, t Transition, collectPredicates, inContext, fullCtx, treatEOFAsEpsilon bool) ATNConfig {
-
- switch t.getSerializationType() {
- case TransitionRULE:
- return p.ruleTransition(config, t.(*RuleTransition))
- case TransitionPRECEDENCE:
- return p.precedenceTransition(config, t.(*PrecedencePredicateTransition), collectPredicates, inContext, fullCtx)
- case TransitionPREDICATE:
- return p.predTransition(config, t.(*PredicateTransition), collectPredicates, inContext, fullCtx)
- case TransitionACTION:
- return p.actionTransition(config, t.(*ActionTransition))
- case TransitionEPSILON:
- return NewBaseATNConfig4(config, t.getTarget())
- case TransitionATOM:
- // EOF transitions act like epsilon transitions after the first EOF
- // transition is traversed
- if treatEOFAsEpsilon {
- if t.Matches(TokenEOF, 0, 1) {
- return NewBaseATNConfig4(config, t.getTarget())
- }
- }
- return nil
- case TransitionRANGE:
- // EOF transitions act like epsilon transitions after the first EOF
- // transition is traversed
- if treatEOFAsEpsilon {
- if t.Matches(TokenEOF, 0, 1) {
- return NewBaseATNConfig4(config, t.getTarget())
- }
- }
- return nil
- case TransitionSET:
- // EOF transitions act like epsilon transitions after the first EOF
- // transition is traversed
- if treatEOFAsEpsilon {
- if t.Matches(TokenEOF, 0, 1) {
- return NewBaseATNConfig4(config, t.getTarget())
- }
- }
- return nil
- default:
- return nil
- }
-}
-
-func (p *ParserATNSimulator) actionTransition(config ATNConfig, t *ActionTransition) *BaseATNConfig {
- if ParserATNSimulatorDebug {
- fmt.Println("ACTION edge " + strconv.Itoa(t.ruleIndex) + ":" + strconv.Itoa(t.actionIndex))
- }
- return NewBaseATNConfig4(config, t.getTarget())
-}
-
-func (p *ParserATNSimulator) precedenceTransition(config ATNConfig,
- pt *PrecedencePredicateTransition, collectPredicates, inContext, fullCtx bool) *BaseATNConfig {
-
- if ParserATNSimulatorDebug {
- fmt.Println("PRED (collectPredicates=" + fmt.Sprint(collectPredicates) + ") " +
- strconv.Itoa(pt.precedence) + ">=_p, ctx dependent=true")
- if p.parser != nil {
- fmt.Println("context surrounding pred is " + fmt.Sprint(p.parser.GetRuleInvocationStack(nil)))
- }
- }
- var c *BaseATNConfig
- if collectPredicates && inContext {
- if fullCtx {
- // In full context mode, we can evaluate predicates on-the-fly
- // during closure, which dramatically reduces the size of
- // the config sets. It also obviates the need to test predicates
- // later during conflict resolution.
- currentPosition := p.input.Index()
- p.input.Seek(p.startIndex)
- predSucceeds := pt.getPredicate().evaluate(p.parser, p.outerContext)
- p.input.Seek(currentPosition)
- if predSucceeds {
- c = NewBaseATNConfig4(config, pt.getTarget()) // no pred context
- }
- } else {
- newSemCtx := SemanticContextandContext(config.GetSemanticContext(), pt.getPredicate())
- c = NewBaseATNConfig3(config, pt.getTarget(), newSemCtx)
- }
- } else {
- c = NewBaseATNConfig4(config, pt.getTarget())
- }
- if ParserATNSimulatorDebug {
- fmt.Println("config from pred transition=" + c.String())
- }
- return c
-}
-
-func (p *ParserATNSimulator) predTransition(config ATNConfig, pt *PredicateTransition, collectPredicates, inContext, fullCtx bool) *BaseATNConfig {
-
- if ParserATNSimulatorDebug {
- fmt.Println("PRED (collectPredicates=" + fmt.Sprint(collectPredicates) + ") " + strconv.Itoa(pt.ruleIndex) +
- ":" + strconv.Itoa(pt.predIndex) + ", ctx dependent=" + fmt.Sprint(pt.isCtxDependent))
- if p.parser != nil {
- fmt.Println("context surrounding pred is " + fmt.Sprint(p.parser.GetRuleInvocationStack(nil)))
- }
- }
- var c *BaseATNConfig
- if collectPredicates && ((pt.isCtxDependent && inContext) || !pt.isCtxDependent) {
- if fullCtx {
- // In full context mode, we can evaluate predicates on-the-fly
- // during closure, which dramatically reduces the size of
- // the config sets. It also obviates the need to test predicates
- // later during conflict resolution.
- currentPosition := p.input.Index()
- p.input.Seek(p.startIndex)
- predSucceeds := pt.getPredicate().evaluate(p.parser, p.outerContext)
- p.input.Seek(currentPosition)
- if predSucceeds {
- c = NewBaseATNConfig4(config, pt.getTarget()) // no pred context
- }
- } else {
- newSemCtx := SemanticContextandContext(config.GetSemanticContext(), pt.getPredicate())
- c = NewBaseATNConfig3(config, pt.getTarget(), newSemCtx)
- }
- } else {
- c = NewBaseATNConfig4(config, pt.getTarget())
- }
- if ParserATNSimulatorDebug {
- fmt.Println("config from pred transition=" + c.String())
- }
- return c
-}
-
-func (p *ParserATNSimulator) ruleTransition(config ATNConfig, t *RuleTransition) *BaseATNConfig {
- if ParserATNSimulatorDebug {
- fmt.Println("CALL rule " + p.getRuleName(t.getTarget().GetRuleIndex()) + ", ctx=" + config.GetContext().String())
- }
- returnState := t.followState
- newContext := SingletonBasePredictionContextCreate(config.GetContext(), returnState.GetStateNumber())
- return NewBaseATNConfig1(config, t.getTarget(), newContext)
-}
-
-func (p *ParserATNSimulator) getConflictingAlts(configs ATNConfigSet) *BitSet {
- altsets := PredictionModegetConflictingAltSubsets(configs)
- return PredictionModeGetAlts(altsets)
-}
-
-// Sam pointed out a problem with the previous definition, v3, of
-// ambiguous states. If we have another state associated with conflicting
-// alternatives, we should keep going. For example, the following grammar
-//
-// s : (ID | ID ID?) ''
-//
-// When the ATN simulation reaches the state before '', it has a DFA
-// state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
-// 12|1|[] and 12|2|[] conflict, but we cannot stop processing p node
-// because alternative to has another way to continue, via [6|2|[]].
-// The key is that we have a single state that has config's only associated
-// with a single alternative, 2, and crucially the state transitions
-// among the configurations are all non-epsilon transitions. That means
-// we don't consider any conflicts that include alternative 2. So, we
-// ignore the conflict between alts 1 and 2. We ignore a set of
-// conflicting alts when there is an intersection with an alternative
-// associated with a single alt state in the state&rarrconfig-list map.
-//
-// It's also the case that we might have two conflicting configurations but
-// also a 3rd nonconflicting configuration for a different alternative:
-// [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
-//
-// a : A | A | A B
-//
-// After Matching input A, we reach the stop state for rule A, state 1.
-// State 8 is the state right before B. Clearly alternatives 1 and 2
-// conflict and no amount of further lookahead will separate the two.
-// However, alternative 3 will be able to continue and so we do not
-// stop working on p state. In the previous example, we're concerned
-// with states associated with the conflicting alternatives. Here alt
-// 3 is not associated with the conflicting configs, but since we can continue
-// looking for input reasonably, I don't declare the state done. We
-// ignore a set of conflicting alts when we have an alternative
-// that we still need to pursue.
-//
-
-func (p *ParserATNSimulator) getConflictingAltsOrUniqueAlt(configs ATNConfigSet) *BitSet {
- var conflictingAlts *BitSet
- if configs.GetUniqueAlt() != ATNInvalidAltNumber {
- conflictingAlts = NewBitSet()
- conflictingAlts.add(configs.GetUniqueAlt())
- } else {
- conflictingAlts = configs.GetConflictingAlts()
- }
- return conflictingAlts
-}
-
-func (p *ParserATNSimulator) GetTokenName(t int) string {
- if t == TokenEOF {
- return "EOF"
- }
-
- if p.parser != nil && p.parser.GetLiteralNames() != nil {
- if t >= len(p.parser.GetLiteralNames()) {
- fmt.Println(strconv.Itoa(t) + " ttype out of range: " + strings.Join(p.parser.GetLiteralNames(), ","))
- // fmt.Println(p.parser.GetInputStream().(TokenStream).GetAllText()) // p seems incorrect
- } else {
- return p.parser.GetLiteralNames()[t] + "<" + strconv.Itoa(t) + ">"
- }
- }
-
- return strconv.Itoa(t)
-}
-
-func (p *ParserATNSimulator) getLookaheadName(input TokenStream) string {
- return p.GetTokenName(input.LA(1))
-}
-
-// Used for debugging in AdaptivePredict around execATN but I cut
-// it out for clarity now that alg. works well. We can leave p
-// "dead" code for a bit.
-//
-func (p *ParserATNSimulator) dumpDeadEndConfigs(nvae *NoViableAltException) {
-
- panic("Not implemented")
-
- // fmt.Println("dead end configs: ")
- // var decs = nvae.deadEndConfigs
- //
- // for i:=0; i0) {
- // var t = c.state.GetTransitions()[0]
- // if t2, ok := t.(*AtomTransition); ok {
- // trans = "Atom "+ p.GetTokenName(t2.label)
- // } else if t3, ok := t.(SetTransition); ok {
- // _, ok := t.(*NotSetTransition)
- //
- // var s string
- // if (ok){
- // s = "~"
- // }
- //
- // trans = s + "Set " + t3.set
- // }
- // }
- // fmt.Errorf(c.String(p.parser, true) + ":" + trans)
- // }
-}
-
-func (p *ParserATNSimulator) noViableAlt(input TokenStream, outerContext ParserRuleContext, configs ATNConfigSet, startIndex int) *NoViableAltException {
- return NewNoViableAltException(p.parser, input, input.Get(startIndex), input.LT(1), configs, outerContext)
-}
-
-func (p *ParserATNSimulator) getUniqueAlt(configs ATNConfigSet) int {
- alt := ATNInvalidAltNumber
- for _, c := range configs.GetItems() {
- if alt == ATNInvalidAltNumber {
- alt = c.GetAlt() // found first alt
- } else if c.GetAlt() != alt {
- return ATNInvalidAltNumber
- }
- }
- return alt
-}
-
-//
-// Add an edge to the DFA, if possible. This method calls
-// {@link //addDFAState} to ensure the {@code to} state is present in the
-// DFA. If {@code from} is {@code nil}, or if {@code t} is outside the
-// range of edges that can be represented in the DFA tables, p method
-// returns without adding the edge to the DFA.
-//
-// If {@code to} is {@code nil}, p method returns {@code nil}.
-// Otherwise, p method returns the {@link DFAState} returned by calling
-// {@link //addDFAState} for the {@code to} state.
-//
-// @param dfa The DFA
-// @param from The source state for the edge
-// @param t The input symbol
-// @param to The target state for the edge
-//
-// @return If {@code to} is {@code nil}, p method returns {@code nil}
-// otherwise p method returns the result of calling {@link //addDFAState}
-// on {@code to}
-//
-func (p *ParserATNSimulator) addDFAEdge(dfa *DFA, from *DFAState, t int, to *DFAState) *DFAState {
- if ParserATNSimulatorDebug {
- fmt.Println("EDGE " + from.String() + " -> " + to.String() + " upon " + p.GetTokenName(t))
- }
- if to == nil {
- return nil
- }
- to = p.addDFAState(dfa, to) // used existing if possible not incoming
- if from == nil || t < -1 || t > p.atn.maxTokenType {
- return to
- }
- if from.edges == nil {
- from.edges = make([]*DFAState, p.atn.maxTokenType+1+1)
- }
- from.edges[t+1] = to // connect
-
- if ParserATNSimulatorDebug {
- var names []string
- if p.parser != nil {
- names = p.parser.GetLiteralNames()
- }
-
- fmt.Println("DFA=\n" + dfa.String(names, nil))
- }
- return to
-}
-
-//
-// Add state {@code D} to the DFA if it is not already present, and return
-// the actual instance stored in the DFA. If a state equivalent to {@code D}
-// is already in the DFA, the existing state is returned. Otherwise p
-// method returns {@code D} after adding it to the DFA.
-//
-// If {@code D} is {@link //ERROR}, p method returns {@link //ERROR} and
-// does not change the DFA.
-//
-// @param dfa The dfa
-// @param D The DFA state to add
-// @return The state stored in the DFA. This will be either the existing
-// state if {@code D} is already in the DFA, or {@code D} itself if the
-// state was not already present.
-//
-func (p *ParserATNSimulator) addDFAState(dfa *DFA, d *DFAState) *DFAState {
- if d == ATNSimulatorError {
- return d
- }
- hash := d.hash()
- existing, ok := dfa.getState(hash)
- if ok {
- return existing
- }
- d.stateNumber = dfa.numStates()
- if !d.configs.ReadOnly() {
- d.configs.OptimizeConfigs(p.BaseATNSimulator)
- d.configs.SetReadOnly(true)
- }
- dfa.setState(hash, d)
- if ParserATNSimulatorDebug {
- fmt.Println("adding NewDFA state: " + d.String())
- }
- return d
-}
-
-func (p *ParserATNSimulator) ReportAttemptingFullContext(dfa *DFA, conflictingAlts *BitSet, configs ATNConfigSet, startIndex, stopIndex int) {
- if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
- interval := NewInterval(startIndex, stopIndex+1)
- fmt.Println("ReportAttemptingFullContext decision=" + strconv.Itoa(dfa.decision) + ":" + configs.String() +
- ", input=" + p.parser.GetTokenStream().GetTextFromInterval(interval))
- }
- if p.parser != nil {
- p.parser.GetErrorListenerDispatch().ReportAttemptingFullContext(p.parser, dfa, startIndex, stopIndex, conflictingAlts, configs)
- }
-}
-
-func (p *ParserATNSimulator) ReportContextSensitivity(dfa *DFA, prediction int, configs ATNConfigSet, startIndex, stopIndex int) {
- if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
- interval := NewInterval(startIndex, stopIndex+1)
- fmt.Println("ReportContextSensitivity decision=" + strconv.Itoa(dfa.decision) + ":" + configs.String() +
- ", input=" + p.parser.GetTokenStream().GetTextFromInterval(interval))
- }
- if p.parser != nil {
- p.parser.GetErrorListenerDispatch().ReportContextSensitivity(p.parser, dfa, startIndex, stopIndex, prediction, configs)
- }
-}
-
-// If context sensitive parsing, we know it's ambiguity not conflict//
-func (p *ParserATNSimulator) ReportAmbiguity(dfa *DFA, D *DFAState, startIndex, stopIndex int,
- exact bool, ambigAlts *BitSet, configs ATNConfigSet) {
- if ParserATNSimulatorDebug || ParserATNSimulatorRetryDebug {
- interval := NewInterval(startIndex, stopIndex+1)
- fmt.Println("ReportAmbiguity " + ambigAlts.String() + ":" + configs.String() +
- ", input=" + p.parser.GetTokenStream().GetTextFromInterval(interval))
- }
- if p.parser != nil {
- p.parser.GetErrorListenerDispatch().ReportAmbiguity(p.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs)
- }
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_rule_context.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_rule_context.go
deleted file mode 100644
index 49cd10c..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/parser_rule_context.go
+++ /dev/null
@@ -1,362 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "reflect"
- "strconv"
-)
-
-type ParserRuleContext interface {
- RuleContext
-
- SetException(RecognitionException)
-
- AddTokenNode(token Token) *TerminalNodeImpl
- AddErrorNode(badToken Token) *ErrorNodeImpl
-
- EnterRule(listener ParseTreeListener)
- ExitRule(listener ParseTreeListener)
-
- SetStart(Token)
- GetStart() Token
-
- SetStop(Token)
- GetStop() Token
-
- AddChild(child RuleContext) RuleContext
- RemoveLastChild()
-}
-
-type BaseParserRuleContext struct {
- *BaseRuleContext
-
- start, stop Token
- exception RecognitionException
- children []Tree
-}
-
-func NewBaseParserRuleContext(parent ParserRuleContext, invokingStateNumber int) *BaseParserRuleContext {
- prc := new(BaseParserRuleContext)
-
- prc.BaseRuleContext = NewBaseRuleContext(parent, invokingStateNumber)
-
- prc.RuleIndex = -1
- // * If we are debugging or building a parse tree for a Visitor,
- // we need to track all of the tokens and rule invocations associated
- // with prc rule's context. This is empty for parsing w/o tree constr.
- // operation because we don't the need to track the details about
- // how we parse prc rule.
- // /
- prc.children = nil
- prc.start = nil
- prc.stop = nil
- // The exception that forced prc rule to return. If the rule successfully
- // completed, prc is {@code nil}.
- prc.exception = nil
-
- return prc
-}
-
-func (prc *BaseParserRuleContext) SetException(e RecognitionException) {
- prc.exception = e
-}
-
-func (prc *BaseParserRuleContext) GetChildren() []Tree {
- return prc.children
-}
-
-func (prc *BaseParserRuleContext) CopyFrom(ctx *BaseParserRuleContext) {
- // from RuleContext
- prc.parentCtx = ctx.parentCtx
- prc.invokingState = ctx.invokingState
- prc.children = nil
- prc.start = ctx.start
- prc.stop = ctx.stop
-}
-
-func (prc *BaseParserRuleContext) GetText() string {
- if prc.GetChildCount() == 0 {
- return ""
- }
-
- var s string
- for _, child := range prc.children {
- s += child.(ParseTree).GetText()
- }
-
- return s
-}
-
-// Double dispatch methods for listeners
-func (prc *BaseParserRuleContext) EnterRule(listener ParseTreeListener) {
-}
-
-func (prc *BaseParserRuleContext) ExitRule(listener ParseTreeListener) {
-}
-
-// * Does not set parent link other add methods do that///
-func (prc *BaseParserRuleContext) addTerminalNodeChild(child TerminalNode) TerminalNode {
- if prc.children == nil {
- prc.children = make([]Tree, 0)
- }
- if child == nil {
- panic("Child may not be null")
- }
- prc.children = append(prc.children, child)
- return child
-}
-
-func (prc *BaseParserRuleContext) AddChild(child RuleContext) RuleContext {
- if prc.children == nil {
- prc.children = make([]Tree, 0)
- }
- if child == nil {
- panic("Child may not be null")
- }
- prc.children = append(prc.children, child)
- return child
-}
-
-// * Used by EnterOuterAlt to toss out a RuleContext previously added as
-// we entered a rule. If we have // label, we will need to remove
-// generic ruleContext object.
-// /
-func (prc *BaseParserRuleContext) RemoveLastChild() {
- if prc.children != nil && len(prc.children) > 0 {
- prc.children = prc.children[0 : len(prc.children)-1]
- }
-}
-
-func (prc *BaseParserRuleContext) AddTokenNode(token Token) *TerminalNodeImpl {
-
- node := NewTerminalNodeImpl(token)
- prc.addTerminalNodeChild(node)
- node.parentCtx = prc
- return node
-
-}
-
-func (prc *BaseParserRuleContext) AddErrorNode(badToken Token) *ErrorNodeImpl {
- node := NewErrorNodeImpl(badToken)
- prc.addTerminalNodeChild(node)
- node.parentCtx = prc
- return node
-}
-
-func (prc *BaseParserRuleContext) GetChild(i int) Tree {
- if prc.children != nil && len(prc.children) >= i {
- return prc.children[i]
- }
-
- return nil
-}
-
-func (prc *BaseParserRuleContext) GetChildOfType(i int, childType reflect.Type) RuleContext {
- if childType == nil {
- return prc.GetChild(i).(RuleContext)
- }
-
- for j := 0; j < len(prc.children); j++ {
- child := prc.children[j]
- if reflect.TypeOf(child) == childType {
- if i == 0 {
- return child.(RuleContext)
- }
-
- i--
- }
- }
-
- return nil
-}
-
-func (prc *BaseParserRuleContext) ToStringTree(ruleNames []string, recog Recognizer) string {
- return TreesStringTree(prc, ruleNames, recog)
-}
-
-func (prc *BaseParserRuleContext) GetRuleContext() RuleContext {
- return prc
-}
-
-func (prc *BaseParserRuleContext) Accept(visitor ParseTreeVisitor) interface{} {
- return visitor.VisitChildren(prc)
-}
-
-func (prc *BaseParserRuleContext) SetStart(t Token) {
- prc.start = t
-}
-
-func (prc *BaseParserRuleContext) GetStart() Token {
- return prc.start
-}
-
-func (prc *BaseParserRuleContext) SetStop(t Token) {
- prc.stop = t
-}
-
-func (prc *BaseParserRuleContext) GetStop() Token {
- return prc.stop
-}
-
-func (prc *BaseParserRuleContext) GetToken(ttype int, i int) TerminalNode {
-
- for j := 0; j < len(prc.children); j++ {
- child := prc.children[j]
- if c2, ok := child.(TerminalNode); ok {
- if c2.GetSymbol().GetTokenType() == ttype {
- if i == 0 {
- return c2
- }
-
- i--
- }
- }
- }
- return nil
-}
-
-func (prc *BaseParserRuleContext) GetTokens(ttype int) []TerminalNode {
- if prc.children == nil {
- return make([]TerminalNode, 0)
- }
-
- tokens := make([]TerminalNode, 0)
-
- for j := 0; j < len(prc.children); j++ {
- child := prc.children[j]
- if tchild, ok := child.(TerminalNode); ok {
- if tchild.GetSymbol().GetTokenType() == ttype {
- tokens = append(tokens, tchild)
- }
- }
- }
-
- return tokens
-}
-
-func (prc *BaseParserRuleContext) GetPayload() interface{} {
- return prc
-}
-
-func (prc *BaseParserRuleContext) getChild(ctxType reflect.Type, i int) RuleContext {
- if prc.children == nil || i < 0 || i >= len(prc.children) {
- return nil
- }
-
- j := -1 // what element have we found with ctxType?
- for _, o := range prc.children {
-
- childType := reflect.TypeOf(o)
-
- if childType.Implements(ctxType) {
- j++
- if j == i {
- return o.(RuleContext)
- }
- }
- }
- return nil
-}
-
-// Go lacks generics, so it's not possible for us to return the child with the correct type, but we do
-// check for convertibility
-
-func (prc *BaseParserRuleContext) GetTypedRuleContext(ctxType reflect.Type, i int) RuleContext {
- return prc.getChild(ctxType, i)
-}
-
-func (prc *BaseParserRuleContext) GetTypedRuleContexts(ctxType reflect.Type) []RuleContext {
- if prc.children == nil {
- return make([]RuleContext, 0)
- }
-
- contexts := make([]RuleContext, 0)
-
- for _, child := range prc.children {
- childType := reflect.TypeOf(child)
-
- if childType.ConvertibleTo(ctxType) {
- contexts = append(contexts, child.(RuleContext))
- }
- }
- return contexts
-}
-
-func (prc *BaseParserRuleContext) GetChildCount() int {
- if prc.children == nil {
- return 0
- }
-
- return len(prc.children)
-}
-
-func (prc *BaseParserRuleContext) GetSourceInterval() *Interval {
- if prc.start == nil || prc.stop == nil {
- return TreeInvalidInterval
- }
-
- return NewInterval(prc.start.GetTokenIndex(), prc.stop.GetTokenIndex())
-}
-
-//need to manage circular dependencies, so export now
-
-// Print out a whole tree, not just a node, in LISP format
-// (root child1 .. childN). Print just a node if b is a leaf.
-//
-
-func (prc *BaseParserRuleContext) String(ruleNames []string, stop RuleContext) string {
-
- var p ParserRuleContext = prc
- s := "["
- for p != nil && p != stop {
- if ruleNames == nil {
- if !p.IsEmpty() {
- s += strconv.Itoa(p.GetInvokingState())
- }
- } else {
- ri := p.GetRuleIndex()
- var ruleName string
- if ri >= 0 && ri < len(ruleNames) {
- ruleName = ruleNames[ri]
- } else {
- ruleName = strconv.Itoa(ri)
- }
- s += ruleName
- }
- if p.GetParent() != nil && (ruleNames != nil || !p.GetParent().(ParserRuleContext).IsEmpty()) {
- s += " "
- }
- pi := p.GetParent()
- if pi != nil {
- p = pi.(ParserRuleContext)
- } else {
- p = nil
- }
- }
- s += "]"
- return s
-}
-
-var RuleContextEmpty = NewBaseParserRuleContext(nil, -1)
-
-type InterpreterRuleContext interface {
- ParserRuleContext
-}
-
-type BaseInterpreterRuleContext struct {
- *BaseParserRuleContext
-}
-
-func NewBaseInterpreterRuleContext(parent BaseInterpreterRuleContext, invokingStateNumber, ruleIndex int) *BaseInterpreterRuleContext {
-
- prc := new(BaseInterpreterRuleContext)
-
- prc.BaseParserRuleContext = NewBaseParserRuleContext(parent, invokingStateNumber)
-
- prc.RuleIndex = ruleIndex
-
- return prc
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_context.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_context.go
deleted file mode 100644
index 99acb33..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_context.go
+++ /dev/null
@@ -1,756 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "strconv"
-)
-
-// Represents {@code $} in local context prediction, which means wildcard.
-// {@code//+x =//}.
-// /
-const (
- BasePredictionContextEmptyReturnState = 0x7FFFFFFF
-)
-
-// Represents {@code $} in an array in full context mode, when {@code $}
-// doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
-// {@code $} = {@link //EmptyReturnState}.
-// /
-
-var (
- BasePredictionContextglobalNodeCount = 1
- BasePredictionContextid = BasePredictionContextglobalNodeCount
-)
-
-type PredictionContext interface {
- hash() int
- GetParent(int) PredictionContext
- getReturnState(int) int
- equals(PredictionContext) bool
- length() int
- isEmpty() bool
- hasEmptyPath() bool
- String() string
-}
-
-type BasePredictionContext struct {
- cachedHash int
-}
-
-func NewBasePredictionContext(cachedHash int) *BasePredictionContext {
- pc := new(BasePredictionContext)
- pc.cachedHash = cachedHash
-
- return pc
-}
-
-func (b *BasePredictionContext) isEmpty() bool {
- return false
-}
-
-func calculateHash(parent PredictionContext, returnState int) int {
- h := murmurInit(1)
- h = murmurUpdate(h, parent.hash())
- h = murmurUpdate(h, returnState)
- return murmurFinish(h, 2)
-}
-
-func calculateEmptyHash() int {
- h := murmurInit(1)
- return murmurFinish(h, 0)
-}
-
-// Used to cache {@link BasePredictionContext} objects. Its used for the shared
-// context cash associated with contexts in DFA states. This cache
-// can be used for both lexers and parsers.
-
-type PredictionContextCache struct {
- cache map[PredictionContext]PredictionContext
-}
-
-func NewPredictionContextCache() *PredictionContextCache {
- t := new(PredictionContextCache)
- t.cache = make(map[PredictionContext]PredictionContext)
- return t
-}
-
-// Add a context to the cache and return it. If the context already exists,
-// return that one instead and do not add a Newcontext to the cache.
-// Protect shared cache from unsafe thread access.
-//
-func (p *PredictionContextCache) add(ctx PredictionContext) PredictionContext {
- if ctx == BasePredictionContextEMPTY {
- return BasePredictionContextEMPTY
- }
- existing := p.cache[ctx]
- if existing != nil {
- return existing
- }
- p.cache[ctx] = ctx
- return ctx
-}
-
-func (p *PredictionContextCache) Get(ctx PredictionContext) PredictionContext {
- return p.cache[ctx]
-}
-
-func (p *PredictionContextCache) length() int {
- return len(p.cache)
-}
-
-type SingletonPredictionContext interface {
- PredictionContext
-}
-
-type BaseSingletonPredictionContext struct {
- *BasePredictionContext
-
- parentCtx PredictionContext
- returnState int
-}
-
-func NewBaseSingletonPredictionContext(parent PredictionContext, returnState int) *BaseSingletonPredictionContext {
-
- s := new(BaseSingletonPredictionContext)
- s.BasePredictionContext = NewBasePredictionContext(37)
-
- if parent != nil {
- s.cachedHash = calculateHash(parent, returnState)
- } else {
- s.cachedHash = calculateEmptyHash()
- }
-
- s.parentCtx = parent
- s.returnState = returnState
-
- return s
-}
-
-func SingletonBasePredictionContextCreate(parent PredictionContext, returnState int) PredictionContext {
- if returnState == BasePredictionContextEmptyReturnState && parent == nil {
- // someone can pass in the bits of an array ctx that mean $
- return BasePredictionContextEMPTY
- }
-
- return NewBaseSingletonPredictionContext(parent, returnState)
-}
-
-func (b *BaseSingletonPredictionContext) length() int {
- return 1
-}
-
-func (b *BaseSingletonPredictionContext) GetParent(index int) PredictionContext {
- return b.parentCtx
-}
-
-func (b *BaseSingletonPredictionContext) getReturnState(index int) int {
- return b.returnState
-}
-
-func (b *BaseSingletonPredictionContext) hasEmptyPath() bool {
- return b.returnState == BasePredictionContextEmptyReturnState
-}
-
-func (b *BaseSingletonPredictionContext) equals(other PredictionContext) bool {
- if b == other {
- return true
- } else if _, ok := other.(*BaseSingletonPredictionContext); !ok {
- return false
- } else if b.hash() != other.hash() {
- return false // can't be same if hash is different
- }
-
- otherP := other.(*BaseSingletonPredictionContext)
-
- if b.returnState != other.getReturnState(0) {
- return false
- } else if b.parentCtx == nil {
- return otherP.parentCtx == nil
- }
-
- return b.parentCtx.equals(otherP.parentCtx)
-}
-
-func (b *BaseSingletonPredictionContext) hash() int {
- h := murmurInit(1)
-
- if b.parentCtx == nil {
- return murmurFinish(h, 0)
- }
-
- h = murmurUpdate(h, b.parentCtx.hash())
- h = murmurUpdate(h, b.returnState)
- return murmurFinish(h, 2)
-}
-
-func (b *BaseSingletonPredictionContext) String() string {
- var up string
-
- if b.parentCtx == nil {
- up = ""
- } else {
- up = b.parentCtx.String()
- }
-
- if len(up) == 0 {
- if b.returnState == BasePredictionContextEmptyReturnState {
- return "$"
- }
-
- return strconv.Itoa(b.returnState)
- }
-
- return strconv.Itoa(b.returnState) + " " + up
-}
-
-var BasePredictionContextEMPTY = NewEmptyPredictionContext()
-
-type EmptyPredictionContext struct {
- *BaseSingletonPredictionContext
-}
-
-func NewEmptyPredictionContext() *EmptyPredictionContext {
-
- p := new(EmptyPredictionContext)
-
- p.BaseSingletonPredictionContext = NewBaseSingletonPredictionContext(nil, BasePredictionContextEmptyReturnState)
-
- return p
-}
-
-func (e *EmptyPredictionContext) isEmpty() bool {
- return true
-}
-
-func (e *EmptyPredictionContext) GetParent(index int) PredictionContext {
- return nil
-}
-
-func (e *EmptyPredictionContext) getReturnState(index int) int {
- return e.returnState
-}
-
-func (e *EmptyPredictionContext) equals(other PredictionContext) bool {
- return e == other
-}
-
-func (e *EmptyPredictionContext) String() string {
- return "$"
-}
-
-type ArrayPredictionContext struct {
- *BasePredictionContext
-
- parents []PredictionContext
- returnStates []int
-}
-
-func NewArrayPredictionContext(parents []PredictionContext, returnStates []int) *ArrayPredictionContext {
- // Parent can be nil only if full ctx mode and we make an array
- // from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using
- // nil parent and
- // returnState == {@link //EmptyReturnState}.
-
- c := new(ArrayPredictionContext)
- c.BasePredictionContext = NewBasePredictionContext(37)
-
- for i := range parents {
- c.cachedHash += calculateHash(parents[i], returnStates[i])
- }
-
- c.parents = parents
- c.returnStates = returnStates
-
- return c
-}
-
-func (a *ArrayPredictionContext) GetReturnStates() []int {
- return a.returnStates
-}
-
-func (a *ArrayPredictionContext) hasEmptyPath() bool {
- return a.getReturnState(a.length()-1) == BasePredictionContextEmptyReturnState
-}
-
-func (a *ArrayPredictionContext) isEmpty() bool {
- // since EmptyReturnState can only appear in the last position, we
- // don't need to verify that size==1
- return a.returnStates[0] == BasePredictionContextEmptyReturnState
-}
-
-func (a *ArrayPredictionContext) length() int {
- return len(a.returnStates)
-}
-
-func (a *ArrayPredictionContext) GetParent(index int) PredictionContext {
- return a.parents[index]
-}
-
-func (a *ArrayPredictionContext) getReturnState(index int) int {
- return a.returnStates[index]
-}
-
-func (a *ArrayPredictionContext) equals(other PredictionContext) bool {
- if _, ok := other.(*ArrayPredictionContext); !ok {
- return false
- } else if a.cachedHash != other.hash() {
- return false // can't be same if hash is different
- } else {
- otherP := other.(*ArrayPredictionContext)
- return &a.returnStates == &otherP.returnStates && &a.parents == &otherP.parents
- }
-}
-
-func (a *ArrayPredictionContext) hash() int {
- h := murmurInit(1)
-
- for _, p := range a.parents {
- h = murmurUpdate(h, p.hash())
- }
-
- for _, r := range a.returnStates {
- h = murmurUpdate(h, r)
- }
-
- return murmurFinish(h, 2 * len(a.parents))
-}
-
-func (a *ArrayPredictionContext) String() string {
- if a.isEmpty() {
- return "[]"
- }
-
- s := "["
- for i := 0; i < len(a.returnStates); i++ {
- if i > 0 {
- s = s + ", "
- }
- if a.returnStates[i] == BasePredictionContextEmptyReturnState {
- s = s + "$"
- continue
- }
- s = s + strconv.Itoa(a.returnStates[i])
- if a.parents[i] != nil {
- s = s + " " + a.parents[i].String()
- } else {
- s = s + "nil"
- }
- }
-
- return s + "]"
-}
-
-// Convert a {@link RuleContext} tree to a {@link BasePredictionContext} graph.
-// Return {@link //EMPTY} if {@code outerContext} is empty or nil.
-// /
-func predictionContextFromRuleContext(a *ATN, outerContext RuleContext) PredictionContext {
- if outerContext == nil {
- outerContext = RuleContextEmpty
- }
- // if we are in RuleContext of start rule, s, then BasePredictionContext
- // is EMPTY. Nobody called us. (if we are empty, return empty)
- if outerContext.GetParent() == nil || outerContext == RuleContextEmpty {
- return BasePredictionContextEMPTY
- }
- // If we have a parent, convert it to a BasePredictionContext graph
- parent := predictionContextFromRuleContext(a, outerContext.GetParent().(RuleContext))
- state := a.states[outerContext.GetInvokingState()]
- transition := state.GetTransitions()[0]
-
- return SingletonBasePredictionContextCreate(parent, transition.(*RuleTransition).followState.GetStateNumber())
-}
-
-func merge(a, b PredictionContext, rootIsWildcard bool, mergeCache *DoubleDict) PredictionContext {
- // share same graph if both same
- if a == b {
- return a
- }
-
- ac, ok1 := a.(*BaseSingletonPredictionContext)
- bc, ok2 := b.(*BaseSingletonPredictionContext)
-
- if ok1 && ok2 {
- return mergeSingletons(ac, bc, rootIsWildcard, mergeCache)
- }
- // At least one of a or b is array
- // If one is $ and rootIsWildcard, return $ as// wildcard
- if rootIsWildcard {
- if _, ok := a.(*EmptyPredictionContext); ok {
- return a
- }
- if _, ok := b.(*EmptyPredictionContext); ok {
- return b
- }
- }
- // convert singleton so both are arrays to normalize
- if _, ok := a.(*BaseSingletonPredictionContext); ok {
- a = NewArrayPredictionContext([]PredictionContext{a.GetParent(0)}, []int{a.getReturnState(0)})
- }
- if _, ok := b.(*BaseSingletonPredictionContext); ok {
- b = NewArrayPredictionContext([]PredictionContext{b.GetParent(0)}, []int{b.getReturnState(0)})
- }
- return mergeArrays(a.(*ArrayPredictionContext), b.(*ArrayPredictionContext), rootIsWildcard, mergeCache)
-}
-
-//
-// Merge two {@link SingletonBasePredictionContext} instances.
-//
-// Stack tops equal, parents merge is same return left graph.
-//
-//
-// Same stack top, parents differ merge parents giving array node, then
-// remainders of those graphs. A Newroot node is created to point to the
-// merged parents.
-//
-//
-// Different stack tops pointing to same parent. Make array node for the
-// root where both element in the root point to the same (original)
-// parent.
-//
-//
-// Different stack tops pointing to different parents. Make array node for
-// the root where each element points to the corresponding original
-// parent.
-//
-//
-// @param a the first {@link SingletonBasePredictionContext}
-// @param b the second {@link SingletonBasePredictionContext}
-// @param rootIsWildcard {@code true} if this is a local-context merge,
-// otherwise false to indicate a full-context merge
-// @param mergeCache
-// /
-func mergeSingletons(a, b *BaseSingletonPredictionContext, rootIsWildcard bool, mergeCache *DoubleDict) PredictionContext {
- if mergeCache != nil {
- previous := mergeCache.Get(a.hash(), b.hash())
- if previous != nil {
- return previous.(PredictionContext)
- }
- previous = mergeCache.Get(b.hash(), a.hash())
- if previous != nil {
- return previous.(PredictionContext)
- }
- }
-
- rootMerge := mergeRoot(a, b, rootIsWildcard)
- if rootMerge != nil {
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), rootMerge)
- }
- return rootMerge
- }
- if a.returnState == b.returnState {
- parent := merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache)
- // if parent is same as existing a or b parent or reduced to a parent,
- // return it
- if parent == a.parentCtx {
- return a // ax + bx = ax, if a=b
- }
- if parent == b.parentCtx {
- return b // ax + bx = bx, if a=b
- }
- // else: ax + ay = a'[x,y]
- // merge parents x and y, giving array node with x,y then remainders
- // of those graphs. dup a, a' points at merged array
- // Newjoined parent so create Newsingleton pointing to it, a'
- spc := SingletonBasePredictionContextCreate(parent, a.returnState)
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), spc)
- }
- return spc
- }
- // a != b payloads differ
- // see if we can collapse parents due to $+x parents if local ctx
- var singleParent PredictionContext
- if a == b || (a.parentCtx != nil && a.parentCtx == b.parentCtx) { // ax +
- // bx =
- // [a,b]x
- singleParent = a.parentCtx
- }
- if singleParent != nil { // parents are same
- // sort payloads and use same parent
- payloads := []int{a.returnState, b.returnState}
- if a.returnState > b.returnState {
- payloads[0] = b.returnState
- payloads[1] = a.returnState
- }
- parents := []PredictionContext{singleParent, singleParent}
- apc := NewArrayPredictionContext(parents, payloads)
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), apc)
- }
- return apc
- }
- // parents differ and can't merge them. Just pack together
- // into array can't merge.
- // ax + by = [ax,by]
- payloads := []int{a.returnState, b.returnState}
- parents := []PredictionContext{a.parentCtx, b.parentCtx}
- if a.returnState > b.returnState { // sort by payload
- payloads[0] = b.returnState
- payloads[1] = a.returnState
- parents = []PredictionContext{b.parentCtx, a.parentCtx}
- }
- apc := NewArrayPredictionContext(parents, payloads)
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), apc)
- }
- return apc
-}
-
-//
-// Handle case where at least one of {@code a} or {@code b} is
-// {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used
-// to represent {@link //EMPTY}.
-//
-// Local-Context Merges
-//
-// These local-context merge operations are used when {@code rootIsWildcard}
-// is true.
-//
-// {@link //EMPTY} is superset of any graph return {@link //EMPTY}.
-//
-//
-// {@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is
-// {@code //EMPTY} return left graph.
-//
-//
-// Special case of last merge if local context.
-//
-//
-// Full-Context Merges
-//
-// These full-context merge operations are used when {@code rootIsWildcard}
-// is false.
-//
-//
-//
-// Must keep all contexts {@link //EMPTY} in array is a special value (and
-// nil parent).
-//
-//
-//
-//
-// @param a the first {@link SingletonBasePredictionContext}
-// @param b the second {@link SingletonBasePredictionContext}
-// @param rootIsWildcard {@code true} if this is a local-context merge,
-// otherwise false to indicate a full-context merge
-// /
-func mergeRoot(a, b SingletonPredictionContext, rootIsWildcard bool) PredictionContext {
- if rootIsWildcard {
- if a == BasePredictionContextEMPTY {
- return BasePredictionContextEMPTY // // + b =//
- }
- if b == BasePredictionContextEMPTY {
- return BasePredictionContextEMPTY // a +// =//
- }
- } else {
- if a == BasePredictionContextEMPTY && b == BasePredictionContextEMPTY {
- return BasePredictionContextEMPTY // $ + $ = $
- } else if a == BasePredictionContextEMPTY { // $ + x = [$,x]
- payloads := []int{b.getReturnState(-1), BasePredictionContextEmptyReturnState}
- parents := []PredictionContext{b.GetParent(-1), nil}
- return NewArrayPredictionContext(parents, payloads)
- } else if b == BasePredictionContextEMPTY { // x + $ = [$,x] ($ is always first if present)
- payloads := []int{a.getReturnState(-1), BasePredictionContextEmptyReturnState}
- parents := []PredictionContext{a.GetParent(-1), nil}
- return NewArrayPredictionContext(parents, payloads)
- }
- }
- return nil
-}
-
-//
-// Merge two {@link ArrayBasePredictionContext} instances.
-//
-// Different tops, different parents.
-//
-//
-// Shared top, same parents.
-//
-//
-// Shared top, different parents.
-//
-//
-// Shared top, all shared parents.
-//
-//
-// Equal tops, merge parents and reduce top to
-// {@link SingletonBasePredictionContext}.
-//
-// /
-func mergeArrays(a, b *ArrayPredictionContext, rootIsWildcard bool, mergeCache *DoubleDict) PredictionContext {
- if mergeCache != nil {
- previous := mergeCache.Get(a.hash(), b.hash())
- if previous != nil {
- return previous.(PredictionContext)
- }
- previous = mergeCache.Get(b.hash(), a.hash())
- if previous != nil {
- return previous.(PredictionContext)
- }
- }
- // merge sorted payloads a + b => M
- i := 0 // walks a
- j := 0 // walks b
- k := 0 // walks target M array
-
- mergedReturnStates := make([]int, len(a.returnStates)+len(b.returnStates))
- mergedParents := make([]PredictionContext, len(a.returnStates)+len(b.returnStates))
- // walk and merge to yield mergedParents, mergedReturnStates
- for i < len(a.returnStates) && j < len(b.returnStates) {
- aParent := a.parents[i]
- bParent := b.parents[j]
- if a.returnStates[i] == b.returnStates[j] {
- // same payload (stack tops are equal), must yield merged singleton
- payload := a.returnStates[i]
- // $+$ = $
- bothDollars := payload == BasePredictionContextEmptyReturnState && aParent == nil && bParent == nil
- axAX := (aParent != nil && bParent != nil && aParent == bParent) // ax+ax
- // ->
- // ax
- if bothDollars || axAX {
- mergedParents[k] = aParent // choose left
- mergedReturnStates[k] = payload
- } else { // ax+ay -> a'[x,y]
- mergedParent := merge(aParent, bParent, rootIsWildcard, mergeCache)
- mergedParents[k] = mergedParent
- mergedReturnStates[k] = payload
- }
- i++ // hop over left one as usual
- j++ // but also Skip one in right side since we merge
- } else if a.returnStates[i] < b.returnStates[j] { // copy a[i] to M
- mergedParents[k] = aParent
- mergedReturnStates[k] = a.returnStates[i]
- i++
- } else { // b > a, copy b[j] to M
- mergedParents[k] = bParent
- mergedReturnStates[k] = b.returnStates[j]
- j++
- }
- k++
- }
- // copy over any payloads remaining in either array
- if i < len(a.returnStates) {
- for p := i; p < len(a.returnStates); p++ {
- mergedParents[k] = a.parents[p]
- mergedReturnStates[k] = a.returnStates[p]
- k++
- }
- } else {
- for p := j; p < len(b.returnStates); p++ {
- mergedParents[k] = b.parents[p]
- mergedReturnStates[k] = b.returnStates[p]
- k++
- }
- }
- // trim merged if we combined a few that had same stack tops
- if k < len(mergedParents) { // write index < last position trim
- if k == 1 { // for just one merged element, return singleton top
- pc := SingletonBasePredictionContextCreate(mergedParents[0], mergedReturnStates[0])
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), pc)
- }
- return pc
- }
- mergedParents = mergedParents[0:k]
- mergedReturnStates = mergedReturnStates[0:k]
- }
-
- M := NewArrayPredictionContext(mergedParents, mergedReturnStates)
-
- // if we created same array as a or b, return that instead
- // TODO: track whether this is possible above during merge sort for speed
- if M == a {
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), a)
- }
- return a
- }
- if M == b {
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), b)
- }
- return b
- }
- combineCommonParents(mergedParents)
-
- if mergeCache != nil {
- mergeCache.set(a.hash(), b.hash(), M)
- }
- return M
-}
-
-//
-// Make pass over all M {@code parents} merge any {@code equals()}
-// ones.
-// /
-func combineCommonParents(parents []PredictionContext) {
- uniqueParents := make(map[PredictionContext]PredictionContext)
-
- for p := 0; p < len(parents); p++ {
- parent := parents[p]
- if uniqueParents[parent] == nil {
- uniqueParents[parent] = parent
- }
- }
- for q := 0; q < len(parents); q++ {
- parents[q] = uniqueParents[parents[q]]
- }
-}
-
-func getCachedBasePredictionContext(context PredictionContext, contextCache *PredictionContextCache, visited map[PredictionContext]PredictionContext) PredictionContext {
-
- if context.isEmpty() {
- return context
- }
- existing := visited[context]
- if existing != nil {
- return existing
- }
- existing = contextCache.Get(context)
- if existing != nil {
- visited[context] = existing
- return existing
- }
- changed := false
- parents := make([]PredictionContext, context.length())
- for i := 0; i < len(parents); i++ {
- parent := getCachedBasePredictionContext(context.GetParent(i), contextCache, visited)
- if changed || parent != context.GetParent(i) {
- if !changed {
- parents = make([]PredictionContext, context.length())
- for j := 0; j < context.length(); j++ {
- parents[j] = context.GetParent(j)
- }
- changed = true
- }
- parents[i] = parent
- }
- }
- if !changed {
- contextCache.add(context)
- visited[context] = context
- return context
- }
- var updated PredictionContext
- if len(parents) == 0 {
- updated = BasePredictionContextEMPTY
- } else if len(parents) == 1 {
- updated = SingletonBasePredictionContextCreate(parents[0], context.getReturnState(0))
- } else {
- updated = NewArrayPredictionContext(parents, context.(*ArrayPredictionContext).GetReturnStates())
- }
- contextCache.add(updated)
- visited[updated] = updated
- visited[context] = updated
-
- return updated
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_mode.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_mode.go
deleted file mode 100644
index 15718f9..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/prediction_mode.go
+++ /dev/null
@@ -1,553 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// This enumeration defines the prediction modes available in ANTLR 4 along with
-// utility methods for analyzing configuration sets for conflicts and/or
-// ambiguities.
-
-const (
- //
- // The SLL(*) prediction mode. This prediction mode ignores the current
- // parser context when making predictions. This is the fastest prediction
- // mode, and provides correct results for many grammars. This prediction
- // mode is more powerful than the prediction mode provided by ANTLR 3, but
- // may result in syntax errors for grammar and input combinations which are
- // not SLL.
- //
- //
- // When using this prediction mode, the parser will either return a correct
- // parse tree (i.e. the same parse tree that would be returned with the
- // {@link //LL} prediction mode), or it will Report a syntax error. If a
- // syntax error is encountered when using the {@link //SLL} prediction mode,
- // it may be due to either an actual syntax error in the input or indicate
- // that the particular combination of grammar and input requires the more
- // powerful {@link //LL} prediction abilities to complete successfully.
- //
- //
- // This prediction mode does not provide any guarantees for prediction
- // behavior for syntactically-incorrect inputs.
- //
- PredictionModeSLL = 0
- //
- // The LL(*) prediction mode. This prediction mode allows the current parser
- // context to be used for resolving SLL conflicts that occur during
- // prediction. This is the fastest prediction mode that guarantees correct
- // parse results for all combinations of grammars with syntactically correct
- // inputs.
- //
- //
- // When using this prediction mode, the parser will make correct decisions
- // for all syntactically-correct grammar and input combinations. However, in
- // cases where the grammar is truly ambiguous this prediction mode might not
- // Report a precise answer for exactly which alternatives are
- // ambiguous.
- //
- //
- // This prediction mode does not provide any guarantees for prediction
- // behavior for syntactically-incorrect inputs.
- //
- PredictionModeLL = 1
- //
- // The LL(*) prediction mode with exact ambiguity detection. In addition to
- // the correctness guarantees provided by the {@link //LL} prediction mode,
- // this prediction mode instructs the prediction algorithm to determine the
- // complete and exact set of ambiguous alternatives for every ambiguous
- // decision encountered while parsing.
- //
- //
- // This prediction mode may be used for diagnosing ambiguities during
- // grammar development. Due to the performance overhead of calculating sets
- // of ambiguous alternatives, this prediction mode should be avoided when
- // the exact results are not necessary.
- //
- //
- // This prediction mode does not provide any guarantees for prediction
- // behavior for syntactically-incorrect inputs.
- //
- PredictionModeLLExactAmbigDetection = 2
-)
-
-//
-// Computes the SLL prediction termination condition.
-//
-//
-// This method computes the SLL prediction termination condition for both of
-// the following cases.
-//
-//
-// - The usual SLL+LL fallback upon SLL conflict
-// - Pure SLL without LL fallback
-//
-//
-// COMBINED SLL+LL PARSING
-//
-// When LL-fallback is enabled upon SLL conflict, correct predictions are
-// ensured regardless of how the termination condition is computed by this
-// method. Due to the substantially higher cost of LL prediction, the
-// prediction should only fall back to LL when the additional lookahead
-// cannot lead to a unique SLL prediction.
-//
-// Assuming combined SLL+LL parsing, an SLL configuration set with only
-// conflicting subsets should fall back to full LL, even if the
-// configuration sets don't resolve to the same alternative (e.g.
-// {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting
-// configuration, SLL could continue with the hopes that more lookahead will
-// resolve via one of those non-conflicting configurations.
-//
-// Here's the prediction termination rule them: SLL (for SLL+LL parsing)
-// stops when it sees only conflicting configuration subsets. In contrast,
-// full LL keeps going when there is uncertainty.
-//
-// HEURISTIC
-//
-// As a heuristic, we stop prediction when we see any conflicting subset
-// unless we see a state that only has one alternative associated with it.
-// The single-alt-state thing lets prediction continue upon rules like
-// (otherwise, it would admit defeat too soon):
-//
-// {@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) '' }
-//
-// When the ATN simulation reaches the state before {@code ''}, it has a
-// DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally
-// {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop
-// processing this node because alternative to has another way to continue,
-// via {@code [6|2|[]]}.
-//
-// It also let's us continue for this rule:
-//
-// {@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B }
-//
-// After Matching input A, we reach the stop state for rule A, state 1.
-// State 8 is the state right before B. Clearly alternatives 1 and 2
-// conflict and no amount of further lookahead will separate the two.
-// However, alternative 3 will be able to continue and so we do not stop
-// working on this state. In the previous example, we're concerned with
-// states associated with the conflicting alternatives. Here alt 3 is not
-// associated with the conflicting configs, but since we can continue
-// looking for input reasonably, don't declare the state done.
-//
-// PURE SLL PARSING
-//
-// To handle pure SLL parsing, all we have to do is make sure that we
-// combine stack contexts for configurations that differ only by semantic
-// predicate. From there, we can do the usual SLL termination heuristic.
-//
-// PREDICATES IN SLL+LL PARSING
-//
-// SLL decisions don't evaluate predicates until after they reach DFA stop
-// states because they need to create the DFA cache that works in all
-// semantic situations. In contrast, full LL evaluates predicates collected
-// during start state computation so it can ignore predicates thereafter.
-// This means that SLL termination detection can totally ignore semantic
-// predicates.
-//
-// Implementation-wise, {@link ATNConfigSet} combines stack contexts but not
-// semantic predicate contexts so we might see two configurations like the
-// following.
-//
-// {@code (s, 1, x, {}), (s, 1, x', {p})}
-//
-// Before testing these configurations against others, we have to merge
-// {@code x} and {@code x'} (without modifying the existing configurations).
-// For example, we test {@code (x+x')==x''} when looking for conflicts in
-// the following configurations.
-//
-// {@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}
-//
-// If the configuration set has predicates (as indicated by
-// {@link ATNConfigSet//hasSemanticContext}), this algorithm makes a copy of
-// the configurations to strip out all of the predicates so that a standard
-// {@link ATNConfigSet} will merge everything ignoring predicates.
-//
-func PredictionModehasSLLConflictTerminatingPrediction(mode int, configs ATNConfigSet) bool {
- // Configs in rule stop states indicate reaching the end of the decision
- // rule (local context) or end of start rule (full context). If all
- // configs meet this condition, then none of the configurations is able
- // to Match additional input so we terminate prediction.
- //
- if PredictionModeallConfigsInRuleStopStates(configs) {
- return true
- }
- // pure SLL mode parsing
- if mode == PredictionModeSLL {
- // Don't bother with combining configs from different semantic
- // contexts if we can fail over to full LL costs more time
- // since we'll often fail over anyway.
- if configs.HasSemanticContext() {
- // dup configs, tossing out semantic predicates
- dup := NewBaseATNConfigSet(false)
- for _, c := range configs.GetItems() {
-
- // NewBaseATNConfig({semanticContext:}, c)
- c = NewBaseATNConfig2(c, SemanticContextNone)
- dup.Add(c, nil)
- }
- configs = dup
- }
- // now we have combined contexts for configs with dissimilar preds
- }
- // pure SLL or combined SLL+LL mode parsing
- altsets := PredictionModegetConflictingAltSubsets(configs)
- return PredictionModehasConflictingAltSet(altsets) && !PredictionModehasStateAssociatedWithOneAlt(configs)
-}
-
-// Checks if any configuration in {@code configs} is in a
-// {@link RuleStopState}. Configurations meeting this condition have reached
-// the end of the decision rule (local context) or end of start rule (full
-// context).
-//
-// @param configs the configuration set to test
-// @return {@code true} if any configuration in {@code configs} is in a
-// {@link RuleStopState}, otherwise {@code false}
-func PredictionModehasConfigInRuleStopState(configs ATNConfigSet) bool {
- for _, c := range configs.GetItems() {
- if _, ok := c.GetState().(*RuleStopState); ok {
- return true
- }
- }
- return false
-}
-
-// Checks if all configurations in {@code configs} are in a
-// {@link RuleStopState}. Configurations meeting this condition have reached
-// the end of the decision rule (local context) or end of start rule (full
-// context).
-//
-// @param configs the configuration set to test
-// @return {@code true} if all configurations in {@code configs} are in a
-// {@link RuleStopState}, otherwise {@code false}
-func PredictionModeallConfigsInRuleStopStates(configs ATNConfigSet) bool {
-
- for _, c := range configs.GetItems() {
- if _, ok := c.GetState().(*RuleStopState); !ok {
- return false
- }
- }
- return true
-}
-
-//
-// Full LL prediction termination.
-//
-// Can we stop looking ahead during ATN simulation or is there some
-// uncertainty as to which alternative we will ultimately pick, after
-// consuming more input? Even if there are partial conflicts, we might know
-// that everything is going to resolve to the same minimum alternative. That
-// means we can stop since no more lookahead will change that fact. On the
-// other hand, there might be multiple conflicts that resolve to different
-// minimums. That means we need more look ahead to decide which of those
-// alternatives we should predict.
-//
-// The basic idea is to split the set of configurations {@code C}, into
-// conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with
-// non-conflicting configurations. Two configurations conflict if they have
-// identical {@link ATNConfig//state} and {@link ATNConfig//context} values
-// but different {@link ATNConfig//alt} value, e.g. {@code (s, i, ctx, _)}
-// and {@code (s, j, ctx, _)} for {@code i!=j}.
-//
-// Reduce these configuration subsets to the set of possible alternatives.
-// You can compute the alternative subsets in one pass as follows:
-//
-// {@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in
-// {@code C} holding {@code s} and {@code ctx} fixed.
-//
-// Or in pseudo-code, for each configuration {@code c} in {@code C}:
-//
-//
-// map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
-// alt and not pred
-//
-//
-// The values in {@code map} are the set of {@code A_s,ctx} sets.
-//
-// If {@code |A_s,ctx|=1} then there is no conflict associated with
-// {@code s} and {@code ctx}.
-//
-// Reduce the subsets to singletons by choosing a minimum of each subset. If
-// the union of these alternative subsets is a singleton, then no amount of
-// more lookahead will help us. We will always pick that alternative. If,
-// however, there is more than one alternative, then we are uncertain which
-// alternative to predict and must continue looking for resolution. We may
-// or may not discover an ambiguity in the future, even if there are no
-// conflicting subsets this round.
-//
-// The biggest sin is to terminate early because it means we've made a
-// decision but were uncertain as to the eventual outcome. We haven't used
-// enough lookahead. On the other hand, announcing a conflict too late is no
-// big deal you will still have the conflict. It's just inefficient. It
-// might even look until the end of file.
-//
-// No special consideration for semantic predicates is required because
-// predicates are evaluated on-the-fly for full LL prediction, ensuring that
-// no configuration contains a semantic context during the termination
-// check.
-//
-// CONFLICTING CONFIGS
-//
-// Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict
-// when {@code i!=j} but {@code x=x'}. Because we merge all
-// {@code (s, i, _)} configurations together, that means that there are at
-// most {@code n} configurations associated with state {@code s} for
-// {@code n} possible alternatives in the decision. The merged stacks
-// complicate the comparison of configuration contexts {@code x} and
-// {@code x'}. Sam checks to see if one is a subset of the other by calling
-// merge and checking to see if the merged result is either {@code x} or
-// {@code x'}. If the {@code x} associated with lowest alternative {@code i}
-// is the superset, then {@code i} is the only possible prediction since the
-// others resolve to {@code min(i)} as well. However, if {@code x} is
-// associated with {@code j>i} then at least one stack configuration for
-// {@code j} is not in conflict with alternative {@code i}. The algorithm
-// should keep going, looking for more lookahead due to the uncertainty.
-//
-// For simplicity, I'm doing a equality check between {@code x} and
-// {@code x'} that lets the algorithm continue to consume lookahead longer
-// than necessary. The reason I like the equality is of course the
-// simplicity but also because that is the test you need to detect the
-// alternatives that are actually in conflict.
-//
-// CONTINUE/STOP RULE
-//
-// Continue if union of resolved alternative sets from non-conflicting and
-// conflicting alternative subsets has more than one alternative. We are
-// uncertain about which alternative to predict.
-//
-// The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which
-// alternatives are still in the running for the amount of input we've
-// consumed at this point. The conflicting sets let us to strip away
-// configurations that won't lead to more states because we resolve
-// conflicts to the configuration with a minimum alternate for the
-// conflicting set.
-//
-// CASES
-//
-//
-//
-// - no conflicts and more than 1 alternative in set => continue
-//
-// - {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},
-// {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set
-// {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
-// {@code {1,3}} => continue
-//
-//
-// - {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
-// {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set
-// {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
-// {@code {1}} => stop and predict 1
-//
-// - {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
-// {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U
-// {@code {1}} = {@code {1}} => stop and predict 1, can announce
-// ambiguity {@code {1,2}}
-//
-// - {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},
-// {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U
-// {@code {2}} = {@code {1,2}} => continue
-//
-// - {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},
-// {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U
-// {@code {3}} = {@code {1,3}} => continue
-//
-//
-//
-// EXACT AMBIGUITY DETECTION
-//
-// If all states Report the same conflicting set of alternatives, then we
-// know we have the exact ambiguity set.
-//
-// |A_i|>1 and
-// A_i = A_j for all i, j.
-//
-// In other words, we continue examining lookahead until all {@code A_i}
-// have more than one alternative and all {@code A_i} are the same. If
-// {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate
-// because the resolved set is {@code {1}}. To determine what the real
-// ambiguity is, we have to know whether the ambiguity is between one and
-// two or one and three so we keep going. We can only stop prediction when
-// we need exact ambiguity detection when the sets look like
-// {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...
-//
-func PredictionModeresolvesToJustOneViableAlt(altsets []*BitSet) int {
- return PredictionModegetSingleViableAlt(altsets)
-}
-
-//
-// Determines if every alternative subset in {@code altsets} contains more
-// than one alternative.
-//
-// @param altsets a collection of alternative subsets
-// @return {@code true} if every {@link BitSet} in {@code altsets} has
-// {@link BitSet//cardinality cardinality} > 1, otherwise {@code false}
-//
-func PredictionModeallSubsetsConflict(altsets []*BitSet) bool {
- return !PredictionModehasNonConflictingAltSet(altsets)
-}
-
-//
-// Determines if any single alternative subset in {@code altsets} contains
-// exactly one alternative.
-//
-// @param altsets a collection of alternative subsets
-// @return {@code true} if {@code altsets} contains a {@link BitSet} with
-// {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
-//
-func PredictionModehasNonConflictingAltSet(altsets []*BitSet) bool {
- for i := 0; i < len(altsets); i++ {
- alts := altsets[i]
- if alts.length() == 1 {
- return true
- }
- }
- return false
-}
-
-//
-// Determines if any single alternative subset in {@code altsets} contains
-// more than one alternative.
-//
-// @param altsets a collection of alternative subsets
-// @return {@code true} if {@code altsets} contains a {@link BitSet} with
-// {@link BitSet//cardinality cardinality} > 1, otherwise {@code false}
-//
-func PredictionModehasConflictingAltSet(altsets []*BitSet) bool {
- for i := 0; i < len(altsets); i++ {
- alts := altsets[i]
- if alts.length() > 1 {
- return true
- }
- }
- return false
-}
-
-//
-// Determines if every alternative subset in {@code altsets} is equivalent.
-//
-// @param altsets a collection of alternative subsets
-// @return {@code true} if every member of {@code altsets} is equal to the
-// others, otherwise {@code false}
-//
-func PredictionModeallSubsetsEqual(altsets []*BitSet) bool {
- var first *BitSet
-
- for i := 0; i < len(altsets); i++ {
- alts := altsets[i]
- if first == nil {
- first = alts
- } else if alts != first {
- return false
- }
- }
-
- return true
-}
-
-//
-// Returns the unique alternative predicted by all alternative subsets in
-// {@code altsets}. If no such alternative exists, this method returns
-// {@link ATN//INVALID_ALT_NUMBER}.
-//
-// @param altsets a collection of alternative subsets
-//
-func PredictionModegetUniqueAlt(altsets []*BitSet) int {
- all := PredictionModeGetAlts(altsets)
- if all.length() == 1 {
- return all.minValue()
- }
-
- return ATNInvalidAltNumber
-}
-
-// Gets the complete set of represented alternatives for a collection of
-// alternative subsets. This method returns the union of each {@link BitSet}
-// in {@code altsets}.
-//
-// @param altsets a collection of alternative subsets
-// @return the set of represented alternatives in {@code altsets}
-//
-func PredictionModeGetAlts(altsets []*BitSet) *BitSet {
- all := NewBitSet()
- for _, alts := range altsets {
- all.or(alts)
- }
- return all
-}
-
-//
-// This func gets the conflicting alt subsets from a configuration set.
-// For each configuration {@code c} in {@code configs}:
-//
-//
-// map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
-// alt and not pred
-//
-//
-func PredictionModegetConflictingAltSubsets(configs ATNConfigSet) []*BitSet {
- configToAlts := make(map[int]*BitSet)
-
- for _, c := range configs.GetItems() {
- key := 31 * c.GetState().GetStateNumber() + c.GetContext().hash()
-
- alts, ok := configToAlts[key]
- if !ok {
- alts = NewBitSet()
- configToAlts[key] = alts
- }
- alts.add(c.GetAlt())
- }
-
- values := make([]*BitSet, 0, 10)
- for _, v := range configToAlts {
- values = append(values, v)
- }
- return values
-}
-
-//
-// Get a map from state to alt subset from a configuration set. For each
-// configuration {@code c} in {@code configs}:
-//
-//
-// map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
-//
-//
-func PredictionModeGetStateToAltMap(configs ATNConfigSet) *AltDict {
- m := NewAltDict()
-
- for _, c := range configs.GetItems() {
- alts := m.Get(c.GetState().String())
- if alts == nil {
- alts = NewBitSet()
- m.put(c.GetState().String(), alts)
- }
- alts.(*BitSet).add(c.GetAlt())
- }
- return m
-}
-
-func PredictionModehasStateAssociatedWithOneAlt(configs ATNConfigSet) bool {
- values := PredictionModeGetStateToAltMap(configs).values()
- for i := 0; i < len(values); i++ {
- if values[i].(*BitSet).length() == 1 {
- return true
- }
- }
- return false
-}
-
-func PredictionModegetSingleViableAlt(altsets []*BitSet) int {
- result := ATNInvalidAltNumber
-
- for i := 0; i < len(altsets); i++ {
- alts := altsets[i]
- minAlt := alts.minValue()
- if result == ATNInvalidAltNumber {
- result = minAlt
- } else if result != minAlt { // more than 1 viable alt
- return ATNInvalidAltNumber
- }
- }
- return result
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/recognizer.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/recognizer.go
deleted file mode 100644
index 9ea9f6f..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/recognizer.go
+++ /dev/null
@@ -1,217 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strings"
-
- "strconv"
-)
-
-type Recognizer interface {
- GetLiteralNames() []string
- GetSymbolicNames() []string
- GetRuleNames() []string
-
- Sempred(RuleContext, int, int) bool
- Precpred(RuleContext, int) bool
-
- GetState() int
- SetState(int)
- Action(RuleContext, int, int)
- AddErrorListener(ErrorListener)
- RemoveErrorListeners()
- GetATN() *ATN
- GetErrorListenerDispatch() ErrorListener
-}
-
-type BaseRecognizer struct {
- listeners []ErrorListener
- state int
-
- RuleNames []string
- LiteralNames []string
- SymbolicNames []string
- GrammarFileName string
-}
-
-func NewBaseRecognizer() *BaseRecognizer {
- rec := new(BaseRecognizer)
- rec.listeners = []ErrorListener{ConsoleErrorListenerINSTANCE}
- rec.state = -1
- return rec
-}
-
-var tokenTypeMapCache = make(map[string]int)
-var ruleIndexMapCache = make(map[string]int)
-
-func (b *BaseRecognizer) checkVersion(toolVersion string) {
- runtimeVersion := "4.7.2"
- if runtimeVersion != toolVersion {
- fmt.Println("ANTLR runtime and generated code versions disagree: " + runtimeVersion + "!=" + toolVersion)
- }
-}
-
-func (b *BaseRecognizer) Action(context RuleContext, ruleIndex, actionIndex int) {
- panic("action not implemented on Recognizer!")
-}
-
-func (b *BaseRecognizer) AddErrorListener(listener ErrorListener) {
- b.listeners = append(b.listeners, listener)
-}
-
-func (b *BaseRecognizer) RemoveErrorListeners() {
- b.listeners = make([]ErrorListener, 0)
-}
-
-func (b *BaseRecognizer) GetRuleNames() []string {
- return b.RuleNames
-}
-
-func (b *BaseRecognizer) GetTokenNames() []string {
- return b.LiteralNames
-}
-
-func (b *BaseRecognizer) GetSymbolicNames() []string {
- return b.SymbolicNames
-}
-
-func (b *BaseRecognizer) GetLiteralNames() []string {
- return b.LiteralNames
-}
-
-func (b *BaseRecognizer) GetState() int {
- return b.state
-}
-
-func (b *BaseRecognizer) SetState(v int) {
- b.state = v
-}
-
-//func (b *Recognizer) GetTokenTypeMap() {
-// var tokenNames = b.GetTokenNames()
-// if (tokenNames==nil) {
-// panic("The current recognizer does not provide a list of token names.")
-// }
-// var result = tokenTypeMapCache[tokenNames]
-// if(result==nil) {
-// result = tokenNames.reduce(function(o, k, i) { o[k] = i })
-// result.EOF = TokenEOF
-// tokenTypeMapCache[tokenNames] = result
-// }
-// return result
-//}
-
-// Get a map from rule names to rule indexes.
-//
-// Used for XPath and tree pattern compilation.
-//
-func (b *BaseRecognizer) GetRuleIndexMap() map[string]int {
-
- panic("Method not defined!")
- // var ruleNames = b.GetRuleNames()
- // if (ruleNames==nil) {
- // panic("The current recognizer does not provide a list of rule names.")
- // }
- //
- // var result = ruleIndexMapCache[ruleNames]
- // if(result==nil) {
- // result = ruleNames.reduce(function(o, k, i) { o[k] = i })
- // ruleIndexMapCache[ruleNames] = result
- // }
- // return result
-}
-
-func (b *BaseRecognizer) GetTokenType(tokenName string) int {
- panic("Method not defined!")
- // var ttype = b.GetTokenTypeMap()[tokenName]
- // if (ttype !=nil) {
- // return ttype
- // } else {
- // return TokenInvalidType
- // }
-}
-
-//func (b *Recognizer) GetTokenTypeMap() map[string]int {
-// Vocabulary vocabulary = getVocabulary()
-//
-// Synchronized (tokenTypeMapCache) {
-// Map result = tokenTypeMapCache.Get(vocabulary)
-// if (result == null) {
-// result = new HashMap()
-// for (int i = 0; i < GetATN().maxTokenType; i++) {
-// String literalName = vocabulary.getLiteralName(i)
-// if (literalName != null) {
-// result.put(literalName, i)
-// }
-//
-// String symbolicName = vocabulary.GetSymbolicName(i)
-// if (symbolicName != null) {
-// result.put(symbolicName, i)
-// }
-// }
-//
-// result.put("EOF", Token.EOF)
-// result = Collections.unmodifiableMap(result)
-// tokenTypeMapCache.put(vocabulary, result)
-// }
-//
-// return result
-// }
-//}
-
-// What is the error header, normally line/character position information?//
-func (b *BaseRecognizer) GetErrorHeader(e RecognitionException) string {
- line := e.GetOffendingToken().GetLine()
- column := e.GetOffendingToken().GetColumn()
- return "line " + strconv.Itoa(line) + ":" + strconv.Itoa(column)
-}
-
-// How should a token be displayed in an error message? The default
-// is to display just the text, but during development you might
-// want to have a lot of information spit out. Override in that case
-// to use t.String() (which, for CommonToken, dumps everything about
-// the token). This is better than forcing you to override a method in
-// your token objects because you don't have to go modify your lexer
-// so that it creates a NewJava type.
-//
-// @deprecated This method is not called by the ANTLR 4 Runtime. Specific
-// implementations of {@link ANTLRErrorStrategy} may provide a similar
-// feature when necessary. For example, see
-// {@link DefaultErrorStrategy//GetTokenErrorDisplay}.
-//
-func (b *BaseRecognizer) GetTokenErrorDisplay(t Token) string {
- if t == nil {
- return ""
- }
- s := t.GetText()
- if s == "" {
- if t.GetTokenType() == TokenEOF {
- s = ""
- } else {
- s = "<" + strconv.Itoa(t.GetTokenType()) + ">"
- }
- }
- s = strings.Replace(s, "\t", "\\t", -1)
- s = strings.Replace(s, "\n", "\\n", -1)
- s = strings.Replace(s, "\r", "\\r", -1)
-
- return "'" + s + "'"
-}
-
-func (b *BaseRecognizer) GetErrorListenerDispatch() ErrorListener {
- return NewProxyErrorListener(b.listeners)
-}
-
-// subclass needs to override these if there are sempreds or actions
-// that the ATN interp needs to execute
-func (b *BaseRecognizer) Sempred(localctx RuleContext, ruleIndex int, actionIndex int) bool {
- return true
-}
-
-func (b *BaseRecognizer) Precpred(localctx RuleContext, precedence int) bool {
- return true
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/rule_context.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/rule_context.go
deleted file mode 100644
index 600cf8c..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/rule_context.go
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// A rule context is a record of a single rule invocation. It knows
-// which context invoked it, if any. If there is no parent context, then
-// naturally the invoking state is not valid. The parent link
-// provides a chain upwards from the current rule invocation to the root
-// of the invocation tree, forming a stack. We actually carry no
-// information about the rule associated with b context (except
-// when parsing). We keep only the state number of the invoking state from
-// the ATN submachine that invoked b. Contrast b with the s
-// pointer inside ParserRuleContext that tracks the current state
-// being "executed" for the current rule.
-//
-// The parent contexts are useful for computing lookahead sets and
-// getting error information.
-//
-// These objects are used during parsing and prediction.
-// For the special case of parsers, we use the subclass
-// ParserRuleContext.
-//
-// @see ParserRuleContext
-//
-
-type RuleContext interface {
- RuleNode
-
- GetInvokingState() int
- SetInvokingState(int)
-
- GetRuleIndex() int
- IsEmpty() bool
-
- GetAltNumber() int
- SetAltNumber(altNumber int)
-
- String([]string, RuleContext) string
-}
-
-type BaseRuleContext struct {
- parentCtx RuleContext
- invokingState int
- RuleIndex int
-}
-
-func NewBaseRuleContext(parent RuleContext, invokingState int) *BaseRuleContext {
-
- rn := new(BaseRuleContext)
-
- // What context invoked b rule?
- rn.parentCtx = parent
-
- // What state invoked the rule associated with b context?
- // The "return address" is the followState of invokingState
- // If parent is nil, b should be -1.
- if parent == nil {
- rn.invokingState = -1
- } else {
- rn.invokingState = invokingState
- }
-
- return rn
-}
-
-func (b *BaseRuleContext) GetBaseRuleContext() *BaseRuleContext {
- return b
-}
-
-func (b *BaseRuleContext) SetParent(v Tree) {
- if v == nil {
- b.parentCtx = nil
- } else {
- b.parentCtx = v.(RuleContext)
- }
-}
-
-func (b *BaseRuleContext) GetInvokingState() int {
- return b.invokingState
-}
-
-func (b *BaseRuleContext) SetInvokingState(t int) {
- b.invokingState = t
-}
-
-func (b *BaseRuleContext) GetRuleIndex() int {
- return b.RuleIndex
-}
-
-func (b *BaseRuleContext) GetAltNumber() int {
- return ATNInvalidAltNumber
-}
-
-func (b *BaseRuleContext) SetAltNumber(altNumber int) {}
-
-// A context is empty if there is no invoking state meaning nobody call
-// current context.
-func (b *BaseRuleContext) IsEmpty() bool {
- return b.invokingState == -1
-}
-
-// Return the combined text of all child nodes. This method only considers
-// tokens which have been added to the parse tree.
-//
-// Since tokens on hidden channels (e.g. whitespace or comments) are not
-// added to the parse trees, they will not appear in the output of b
-// method.
-//
-
-func (b *BaseRuleContext) GetParent() Tree {
- return b.parentCtx
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/semantic_context.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/semantic_context.go
deleted file mode 100644
index 49205a1..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/semantic_context.go
+++ /dev/null
@@ -1,455 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "fmt"
- "strconv"
-)
-
-// A tree structure used to record the semantic context in which
-// an ATN configuration is valid. It's either a single predicate,
-// a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
-//
-//
I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
-// {@link SemanticContext} within the scope of this outer class.
-//
-
-type SemanticContext interface {
- comparable
-
- evaluate(parser Recognizer, outerContext RuleContext) bool
- evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext
-
- hash() int
- String() string
-}
-
-func SemanticContextandContext(a, b SemanticContext) SemanticContext {
- if a == nil || a == SemanticContextNone {
- return b
- }
- if b == nil || b == SemanticContextNone {
- return a
- }
- result := NewAND(a, b)
- if len(result.opnds) == 1 {
- return result.opnds[0]
- }
-
- return result
-}
-
-func SemanticContextorContext(a, b SemanticContext) SemanticContext {
- if a == nil {
- return b
- }
- if b == nil {
- return a
- }
- if a == SemanticContextNone || b == SemanticContextNone {
- return SemanticContextNone
- }
- result := NewOR(a, b)
- if len(result.opnds) == 1 {
- return result.opnds[0]
- }
-
- return result
-}
-
-type Predicate struct {
- ruleIndex int
- predIndex int
- isCtxDependent bool
-}
-
-func NewPredicate(ruleIndex, predIndex int, isCtxDependent bool) *Predicate {
- p := new(Predicate)
-
- p.ruleIndex = ruleIndex
- p.predIndex = predIndex
- p.isCtxDependent = isCtxDependent // e.g., $i ref in pred
- return p
-}
-
-//The default {@link SemanticContext}, which is semantically equivalent to
-//a predicate of the form {@code {true}?}.
-
-var SemanticContextNone SemanticContext = NewPredicate(-1, -1, false)
-
-func (p *Predicate) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {
- return p
-}
-
-func (p *Predicate) evaluate(parser Recognizer, outerContext RuleContext) bool {
-
- var localctx RuleContext
-
- if p.isCtxDependent {
- localctx = outerContext
- }
-
- return parser.Sempred(localctx, p.ruleIndex, p.predIndex)
-}
-
-func (p *Predicate) equals(other interface{}) bool {
- if p == other {
- return true
- } else if _, ok := other.(*Predicate); !ok {
- return false
- } else {
- return p.ruleIndex == other.(*Predicate).ruleIndex &&
- p.predIndex == other.(*Predicate).predIndex &&
- p.isCtxDependent == other.(*Predicate).isCtxDependent
- }
-}
-
-func (p *Predicate) hash() int {
- return p.ruleIndex*43 + p.predIndex*47
-}
-
-func (p *Predicate) String() string {
- return "{" + strconv.Itoa(p.ruleIndex) + ":" + strconv.Itoa(p.predIndex) + "}?"
-}
-
-type PrecedencePredicate struct {
- precedence int
-}
-
-func NewPrecedencePredicate(precedence int) *PrecedencePredicate {
-
- p := new(PrecedencePredicate)
- p.precedence = precedence
-
- return p
-}
-
-func (p *PrecedencePredicate) evaluate(parser Recognizer, outerContext RuleContext) bool {
- return parser.Precpred(outerContext, p.precedence)
-}
-
-func (p *PrecedencePredicate) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {
- if parser.Precpred(outerContext, p.precedence) {
- return SemanticContextNone
- }
-
- return nil
-}
-
-func (p *PrecedencePredicate) compareTo(other *PrecedencePredicate) int {
- return p.precedence - other.precedence
-}
-
-func (p *PrecedencePredicate) equals(other interface{}) bool {
- if p == other {
- return true
- } else if _, ok := other.(*PrecedencePredicate); !ok {
- return false
- } else {
- return p.precedence == other.(*PrecedencePredicate).precedence
- }
-}
-
-func (p *PrecedencePredicate) hash() int {
- return p.precedence * 51
-}
-
-func (p *PrecedencePredicate) String() string {
- return "{" + strconv.Itoa(p.precedence) + ">=prec}?"
-}
-
-func PrecedencePredicatefilterPrecedencePredicates(set *Set) []*PrecedencePredicate {
- result := make([]*PrecedencePredicate, 0)
-
- for _, v := range set.values() {
- if c2, ok := v.(*PrecedencePredicate); ok {
- result = append(result, c2)
- }
- }
-
- return result
-}
-
-// A semantic context which is true whenever none of the contained contexts
-// is false.`
-
-type AND struct {
- opnds []SemanticContext
-}
-
-func NewAND(a, b SemanticContext) *AND {
-
- operands := NewSet(nil, nil)
- if aa, ok := a.(*AND); ok {
- for _, o := range aa.opnds {
- operands.add(o)
- }
- } else {
- operands.add(a)
- }
-
- if ba, ok := b.(*AND); ok {
- for _, o := range ba.opnds {
- operands.add(o)
- }
- } else {
- operands.add(b)
- }
- precedencePredicates := PrecedencePredicatefilterPrecedencePredicates(operands)
- if len(precedencePredicates) > 0 {
- // interested in the transition with the lowest precedence
- var reduced *PrecedencePredicate
-
- for _, p := range precedencePredicates {
- if reduced == nil || p.precedence < reduced.precedence {
- reduced = p
- }
- }
-
- operands.add(reduced)
- }
-
- vs := operands.values()
- opnds := make([]SemanticContext, len(vs))
- for i, v := range vs {
- opnds[i] = v.(SemanticContext)
- }
-
- and := new(AND)
- and.opnds = opnds
-
- return and
-}
-
-func (a *AND) equals(other interface{}) bool {
- if a == other {
- return true
- } else if _, ok := other.(*AND); !ok {
- return false
- } else {
- for i, v := range other.(*AND).opnds {
- if !a.opnds[i].equals(v) {
- return false
- }
- }
- return true
- }
-}
-
-//
-// {@inheritDoc}
-//
-//
-// The evaluation of predicates by a context is short-circuiting, but
-// unordered.
-//
-func (a *AND) evaluate(parser Recognizer, outerContext RuleContext) bool {
- for i := 0; i < len(a.opnds); i++ {
- if !a.opnds[i].evaluate(parser, outerContext) {
- return false
- }
- }
- return true
-}
-
-func (a *AND) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {
- differs := false
- operands := make([]SemanticContext, 0)
-
- for i := 0; i < len(a.opnds); i++ {
- context := a.opnds[i]
- evaluated := context.evalPrecedence(parser, outerContext)
- differs = differs || (evaluated != context)
- if evaluated == nil {
- // The AND context is false if any element is false
- return nil
- } else if evaluated != SemanticContextNone {
- // Reduce the result by Skipping true elements
- operands = append(operands, evaluated)
- }
- }
- if !differs {
- return a
- }
-
- if len(operands) == 0 {
- // all elements were true, so the AND context is true
- return SemanticContextNone
- }
-
- var result SemanticContext
-
- for _, o := range operands {
- if result == nil {
- result = o
- } else {
- result = SemanticContextandContext(result, o)
- }
- }
-
- return result
-}
-
-func (a *AND) hash() int {
- h := murmurInit(37) // Init with a value different from OR
- for _, op := range a.opnds {
- h = murmurUpdate(h, op.hash())
- }
- return murmurFinish(h, len(a.opnds))
-}
-
-func (a *OR) hash() int {
- h := murmurInit(41) // Init with a value different from AND
- for _, op := range a.opnds {
- h = murmurUpdate(h, op.hash())
- }
- return murmurFinish(h, len(a.opnds))
-}
-
-func (a *AND) String() string {
- s := ""
-
- for _, o := range a.opnds {
- s += "&& " + fmt.Sprint(o)
- }
-
- if len(s) > 3 {
- return s[0:3]
- }
-
- return s
-}
-
-//
-// A semantic context which is true whenever at least one of the contained
-// contexts is true.
-//
-
-type OR struct {
- opnds []SemanticContext
-}
-
-func NewOR(a, b SemanticContext) *OR {
-
- operands := NewSet(nil, nil)
- if aa, ok := a.(*OR); ok {
- for _, o := range aa.opnds {
- operands.add(o)
- }
- } else {
- operands.add(a)
- }
-
- if ba, ok := b.(*OR); ok {
- for _, o := range ba.opnds {
- operands.add(o)
- }
- } else {
- operands.add(b)
- }
- precedencePredicates := PrecedencePredicatefilterPrecedencePredicates(operands)
- if len(precedencePredicates) > 0 {
- // interested in the transition with the lowest precedence
- var reduced *PrecedencePredicate
-
- for _, p := range precedencePredicates {
- if reduced == nil || p.precedence > reduced.precedence {
- reduced = p
- }
- }
-
- operands.add(reduced)
- }
-
- vs := operands.values()
-
- opnds := make([]SemanticContext, len(vs))
- for i, v := range vs {
- opnds[i] = v.(SemanticContext)
- }
-
- o := new(OR)
- o.opnds = opnds
-
- return o
-}
-
-func (o *OR) equals(other interface{}) bool {
- if o == other {
- return true
- } else if _, ok := other.(*OR); !ok {
- return false
- } else {
- for i, v := range other.(*OR).opnds {
- if !o.opnds[i].equals(v) {
- return false
- }
- }
- return true
- }
-}
-
-//
-// The evaluation of predicates by o context is short-circuiting, but
-// unordered.
-//
-func (o *OR) evaluate(parser Recognizer, outerContext RuleContext) bool {
- for i := 0; i < len(o.opnds); i++ {
- if o.opnds[i].evaluate(parser, outerContext) {
- return true
- }
- }
- return false
-}
-
-func (o *OR) evalPrecedence(parser Recognizer, outerContext RuleContext) SemanticContext {
- differs := false
- operands := make([]SemanticContext, 0)
- for i := 0; i < len(o.opnds); i++ {
- context := o.opnds[i]
- evaluated := context.evalPrecedence(parser, outerContext)
- differs = differs || (evaluated != context)
- if evaluated == SemanticContextNone {
- // The OR context is true if any element is true
- return SemanticContextNone
- } else if evaluated != nil {
- // Reduce the result by Skipping false elements
- operands = append(operands, evaluated)
- }
- }
- if !differs {
- return o
- }
- if len(operands) == 0 {
- // all elements were false, so the OR context is false
- return nil
- }
- var result SemanticContext
-
- for _, o := range operands {
- if result == nil {
- result = o
- } else {
- result = SemanticContextorContext(result, o)
- }
- }
-
- return result
-}
-
-func (o *OR) String() string {
- s := ""
-
- for _, o := range o.opnds {
- s += "|| " + fmt.Sprint(o)
- }
-
- if len(s) > 3 {
- return s[0:3]
- }
-
- return s
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token.go
deleted file mode 100644
index 2d8e990..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token.go
+++ /dev/null
@@ -1,210 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "strconv"
- "strings"
-)
-
-type TokenSourceCharStreamPair struct {
- tokenSource TokenSource
- charStream CharStream
-}
-
-// A token has properties: text, type, line, character position in the line
-// (so we can ignore tabs), token channel, index, and source from which
-// we obtained this token.
-
-type Token interface {
- GetSource() *TokenSourceCharStreamPair
- GetTokenType() int
- GetChannel() int
- GetStart() int
- GetStop() int
- GetLine() int
- GetColumn() int
-
- GetText() string
- SetText(s string)
-
- GetTokenIndex() int
- SetTokenIndex(v int)
-
- GetTokenSource() TokenSource
- GetInputStream() CharStream
-}
-
-type BaseToken struct {
- source *TokenSourceCharStreamPair
- tokenType int // token type of the token
- channel int // The parser ignores everything not on DEFAULT_CHANNEL
- start int // optional return -1 if not implemented.
- stop int // optional return -1 if not implemented.
- tokenIndex int // from 0..n-1 of the token object in the input stream
- line int // line=1..n of the 1st character
- column int // beginning of the line at which it occurs, 0..n-1
- text string // text of the token.
- readOnly bool
-}
-
-const (
- TokenInvalidType = 0
-
- // During lookahead operations, this "token" signifies we hit rule end ATN state
- // and did not follow it despite needing to.
- TokenEpsilon = -2
-
- TokenMinUserTokenType = 1
-
- TokenEOF = -1
-
- // All tokens go to the parser (unless Skip() is called in that rule)
- // on a particular "channel". The parser tunes to a particular channel
- // so that whitespace etc... can go to the parser on a "hidden" channel.
-
- TokenDefaultChannel = 0
-
- // Anything on different channel than DEFAULT_CHANNEL is not parsed
- // by parser.
-
- TokenHiddenChannel = 1
-)
-
-func (b *BaseToken) GetChannel() int {
- return b.channel
-}
-
-func (b *BaseToken) GetStart() int {
- return b.start
-}
-
-func (b *BaseToken) GetStop() int {
- return b.stop
-}
-
-func (b *BaseToken) GetLine() int {
- return b.line
-}
-
-func (b *BaseToken) GetColumn() int {
- return b.column
-}
-
-func (b *BaseToken) GetTokenType() int {
- return b.tokenType
-}
-
-func (b *BaseToken) GetSource() *TokenSourceCharStreamPair {
- return b.source
-}
-
-func (b *BaseToken) GetTokenIndex() int {
- return b.tokenIndex
-}
-
-func (b *BaseToken) SetTokenIndex(v int) {
- b.tokenIndex = v
-}
-
-func (b *BaseToken) GetTokenSource() TokenSource {
- return b.source.tokenSource
-}
-
-func (b *BaseToken) GetInputStream() CharStream {
- return b.source.charStream
-}
-
-type CommonToken struct {
- *BaseToken
-}
-
-func NewCommonToken(source *TokenSourceCharStreamPair, tokenType, channel, start, stop int) *CommonToken {
-
- t := new(CommonToken)
-
- t.BaseToken = new(BaseToken)
-
- t.source = source
- t.tokenType = tokenType
- t.channel = channel
- t.start = start
- t.stop = stop
- t.tokenIndex = -1
- if t.source.tokenSource != nil {
- t.line = source.tokenSource.GetLine()
- t.column = source.tokenSource.GetCharPositionInLine()
- } else {
- t.column = -1
- }
- return t
-}
-
-// An empty {@link Pair} which is used as the default value of
-// {@link //source} for tokens that do not have a source.
-
-//CommonToken.EMPTY_SOURCE = [ nil, nil ]
-
-// Constructs a New{@link CommonToken} as a copy of another {@link Token}.
-//
-//
-// If {@code oldToken} is also a {@link CommonToken} instance, the newly
-// constructed token will share a reference to the {@link //text} field and
-// the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
-// be assigned the result of calling {@link //GetText}, and {@link //source}
-// will be constructed from the result of {@link Token//GetTokenSource} and
-// {@link Token//GetInputStream}.
-//
-// @param oldToken The token to copy.
-//
-func (c *CommonToken) clone() *CommonToken {
- t := NewCommonToken(c.source, c.tokenType, c.channel, c.start, c.stop)
- t.tokenIndex = c.GetTokenIndex()
- t.line = c.GetLine()
- t.column = c.GetColumn()
- t.text = c.GetText()
- return t
-}
-
-func (c *CommonToken) GetText() string {
- if c.text != "" {
- return c.text
- }
- input := c.GetInputStream()
- if input == nil {
- return ""
- }
- n := input.Size()
- if c.start < n && c.stop < n {
- return input.GetTextFromInterval(NewInterval(c.start, c.stop))
- }
- return ""
-}
-
-func (c *CommonToken) SetText(text string) {
- c.text = text
-}
-
-func (c *CommonToken) String() string {
- txt := c.GetText()
- if txt != "" {
- txt = strings.Replace(txt, "\n", "\\n", -1)
- txt = strings.Replace(txt, "\r", "\\r", -1)
- txt = strings.Replace(txt, "\t", "\\t", -1)
- } else {
- txt = ""
- }
-
- var ch string
- if c.channel > 0 {
- ch = ",channel=" + strconv.Itoa(c.channel)
- } else {
- ch = ""
- }
-
- return "[@" + strconv.Itoa(c.tokenIndex) + "," + strconv.Itoa(c.start) + ":" + strconv.Itoa(c.stop) + "='" +
- txt + "',<" + strconv.Itoa(c.tokenType) + ">" +
- ch + "," + strconv.Itoa(c.line) + ":" + strconv.Itoa(c.column) + "]"
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_source.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_source.go
deleted file mode 100644
index e023978..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_source.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type TokenSource interface {
- NextToken() Token
- Skip()
- More()
- GetLine() int
- GetCharPositionInLine() int
- GetInputStream() CharStream
- GetSourceName() string
- setTokenFactory(factory TokenFactory)
- GetTokenFactory() TokenFactory
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_stream.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_stream.go
deleted file mode 100644
index df92c81..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/token_stream.go
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-type TokenStream interface {
- IntStream
-
- LT(k int) Token
-
- Get(index int) Token
- GetTokenSource() TokenSource
- SetTokenSource(TokenSource)
-
- GetAllText() string
- GetTextFromInterval(*Interval) string
- GetTextFromRuleContext(RuleContext) string
- GetTextFromTokens(Token, Token) string
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tokenstream_rewriter.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tokenstream_rewriter.go
deleted file mode 100644
index 96a03f0..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tokenstream_rewriter.go
+++ /dev/null
@@ -1,649 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-package antlr
-
-import (
-"bytes"
-"fmt"
-)
-
-
-//
-// Useful for rewriting out a buffered input token stream after doing some
-// augmentation or other manipulations on it.
-
-//
-// You can insert stuff, replace, and delete chunks. Note that the operations
-// are done lazily--only if you convert the buffer to a {@link String} with
-// {@link TokenStream#getText()}. This is very efficient because you are not
-// moving data around all the time. As the buffer of tokens is converted to
-// strings, the {@link #getText()} method(s) scan the input token stream and
-// check to see if there is an operation at the current index. If so, the
-// operation is done and then normal {@link String} rendering continues on the
-// buffer. This is like having multiple Turing machine instruction streams
-// (programs) operating on a single input tape. :)
-//
-
-// This rewriter makes no modifications to the token stream. It does not ask the
-// stream to fill itself up nor does it advance the input cursor. The token
-// stream {@link TokenStream#index()} will return the same value before and
-// after any {@link #getText()} call.
-
-//
-// The rewriter only works on tokens that you have in the buffer and ignores the
-// current input cursor. If you are buffering tokens on-demand, calling
-// {@link #getText()} halfway through the input will only do rewrites for those
-// tokens in the first half of the file.
-
-//
-// Since the operations are done lazily at {@link #getText}-time, operations do
-// not screw up the token index values. That is, an insert operation at token
-// index {@code i} does not change the index values for tokens
-// {@code i}+1..n-1.
-
-//
-// Because operations never actually alter the buffer, you may always get the
-// original token stream back without undoing anything. Since the instructions
-// are queued up, you can easily simulate transactions and roll back any changes
-// if there is an error just by removing instructions. For example,
-
-//
-// CharStream input = new ANTLRFileStream("input");
-// TLexer lex = new TLexer(input);
-// CommonTokenStream tokens = new CommonTokenStream(lex);
-// T parser = new T(tokens);
-// TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);
-// parser.startRule();
-//
-
-//
-// Then in the rules, you can execute (assuming rewriter is visible):
-
-//
-// Token t,u;
-// ...
-// rewriter.insertAfter(t, "text to put after t");}
-// rewriter.insertAfter(u, "text after u");}
-// System.out.println(rewriter.getText());
-//
-
-//
-// You can also have multiple "instruction streams" and get multiple rewrites
-// from a single pass over the input. Just name the instruction streams and use
-// that name again when printing the buffer. This could be useful for generating
-// a C file and also its header file--all from the same buffer:
-
-//
-// rewriter.insertAfter("pass1", t, "text to put after t");}
-// rewriter.insertAfter("pass2", u, "text after u");}
-// System.out.println(rewriter.getText("pass1"));
-// System.out.println(rewriter.getText("pass2"));
-//
-
-//
-// If you don't use named rewrite streams, a "default" stream is used as the
-// first example shows.
-
-
-
-const(
- Default_Program_Name = "default"
- Program_Init_Size = 100
- Min_Token_Index = 0
-)
-
-// Define the rewrite operation hierarchy
-
-type RewriteOperation interface {
- // Execute the rewrite operation by possibly adding to the buffer.
- // Return the index of the next token to operate on.
- Execute(buffer *bytes.Buffer) int
- String() string
- GetInstructionIndex() int
- GetIndex() int
- GetText() string
- GetOpName() string
- GetTokens() TokenStream
- SetInstructionIndex(val int)
- SetIndex(int)
- SetText(string)
- SetOpName(string)
- SetTokens(TokenStream)
-}
-
-type BaseRewriteOperation struct {
- //Current index of rewrites list
- instruction_index int
- //Token buffer index
- index int
- //Substitution text
- text string
- //Actual operation name
- op_name string
- //Pointer to token steam
- tokens TokenStream
-}
-
-func (op *BaseRewriteOperation)GetInstructionIndex() int{
- return op.instruction_index
-}
-
-func (op *BaseRewriteOperation)GetIndex() int{
- return op.index
-}
-
-func (op *BaseRewriteOperation)GetText() string{
- return op.text
-}
-
-func (op *BaseRewriteOperation)GetOpName() string{
- return op.op_name
-}
-
-func (op *BaseRewriteOperation)GetTokens() TokenStream{
- return op.tokens
-}
-
-func (op *BaseRewriteOperation)SetInstructionIndex(val int){
- op.instruction_index = val
-}
-
-func (op *BaseRewriteOperation)SetIndex(val int) {
- op.index = val
-}
-
-func (op *BaseRewriteOperation)SetText(val string){
- op.text = val
-}
-
-func (op *BaseRewriteOperation)SetOpName(val string){
- op.op_name = val
-}
-
-func (op *BaseRewriteOperation)SetTokens(val TokenStream) {
- op.tokens = val
-}
-
-
-func (op *BaseRewriteOperation) Execute(buffer *bytes.Buffer) int{
- return op.index
-}
-
-func (op *BaseRewriteOperation) String() string {
- return fmt.Sprintf("<%s@%d:\"%s\">",
- op.op_name,
- op.tokens.Get(op.GetIndex()),
- op.text,
- )
-
-}
-
-
-type InsertBeforeOp struct {
- BaseRewriteOperation
-}
-
-func NewInsertBeforeOp(index int, text string, stream TokenStream) *InsertBeforeOp{
- return &InsertBeforeOp{BaseRewriteOperation:BaseRewriteOperation{
- index:index,
- text:text,
- op_name:"InsertBeforeOp",
- tokens:stream,
- }}
-}
-
-func (op *InsertBeforeOp) Execute(buffer *bytes.Buffer) int{
- buffer.WriteString(op.text)
- if op.tokens.Get(op.index).GetTokenType() != TokenEOF{
- buffer.WriteString(op.tokens.Get(op.index).GetText())
- }
- return op.index+1
-}
-
-func (op *InsertBeforeOp) String() string {
- return op.BaseRewriteOperation.String()
-}
-
-// Distinguish between insert after/before to do the "insert afters"
-// first and then the "insert befores" at same index. Implementation
-// of "insert after" is "insert before index+1".
-
-type InsertAfterOp struct {
- BaseRewriteOperation
-}
-
-func NewInsertAfterOp(index int, text string, stream TokenStream) *InsertAfterOp{
- return &InsertAfterOp{BaseRewriteOperation:BaseRewriteOperation{
- index:index+1,
- text:text,
- tokens:stream,
- }}
-}
-
-func (op *InsertAfterOp) Execute(buffer *bytes.Buffer) int {
- buffer.WriteString(op.text)
- if op.tokens.Get(op.index).GetTokenType() != TokenEOF{
- buffer.WriteString(op.tokens.Get(op.index).GetText())
- }
- return op.index+1
-}
-
-func (op *InsertAfterOp) String() string {
- return op.BaseRewriteOperation.String()
-}
-
-// I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp
-// instructions.
-type ReplaceOp struct{
- BaseRewriteOperation
- LastIndex int
-}
-
-func NewReplaceOp(from, to int, text string, stream TokenStream)*ReplaceOp {
- return &ReplaceOp{
- BaseRewriteOperation:BaseRewriteOperation{
- index:from,
- text:text,
- op_name:"ReplaceOp",
- tokens:stream,
- },
- LastIndex:to,
- }
-}
-
-func (op *ReplaceOp)Execute(buffer *bytes.Buffer) int{
- if op.text != ""{
- buffer.WriteString(op.text)
- }
- return op.LastIndex +1
-}
-
-func (op *ReplaceOp) String() string {
- if op.text == "" {
- return fmt.Sprintf("",
- op.tokens.Get(op.index), op.tokens.Get(op.LastIndex))
- }
- return fmt.Sprintf("",
- op.tokens.Get(op.index), op.tokens.Get(op.LastIndex), op.text)
-}
-
-
-type TokenStreamRewriter struct {
- //Our source stream
- tokens TokenStream
- // You may have multiple, named streams of rewrite operations.
- // I'm calling these things "programs."
- // Maps String (name) → rewrite (List)
- programs map[string][]RewriteOperation
- last_rewrite_token_indexes map[string]int
-}
-
-func NewTokenStreamRewriter(tokens TokenStream) *TokenStreamRewriter{
- return &TokenStreamRewriter{
- tokens: tokens,
- programs: map[string][]RewriteOperation{
- Default_Program_Name:make([]RewriteOperation,0, Program_Init_Size),
- },
- last_rewrite_token_indexes: map[string]int{},
- }
-}
-
-func (tsr *TokenStreamRewriter) GetTokenStream() TokenStream{
- return tsr.tokens
-}
-
-// Rollback the instruction stream for a program so that
-// the indicated instruction (via instructionIndex) is no
-// longer in the stream. UNTESTED!
-func (tsr *TokenStreamRewriter) Rollback(program_name string, instruction_index int){
- is, ok := tsr.programs[program_name]
- if ok{
- tsr.programs[program_name] = is[Min_Token_Index:instruction_index]
- }
-}
-
-func (tsr *TokenStreamRewriter) RollbackDefault(instruction_index int){
- tsr.Rollback(Default_Program_Name, instruction_index)
-}
-//Reset the program so that no instructions exist
-func (tsr *TokenStreamRewriter) DeleteProgram(program_name string){
- tsr.Rollback(program_name, Min_Token_Index) //TODO: double test on that cause lower bound is not included
-}
-
-func (tsr *TokenStreamRewriter) DeleteProgramDefault(){
- tsr.DeleteProgram(Default_Program_Name)
-}
-
-func (tsr *TokenStreamRewriter) InsertAfter(program_name string, index int, text string){
- // to insert after, just insert before next index (even if past end)
- var op RewriteOperation = NewInsertAfterOp(index, text, tsr.tokens)
- rewrites := tsr.GetProgram(program_name)
- op.SetInstructionIndex(len(rewrites))
- tsr.AddToProgram(program_name, op)
-}
-
-func (tsr *TokenStreamRewriter) InsertAfterDefault(index int, text string){
- tsr.InsertAfter(Default_Program_Name, index, text)
-}
-
-func (tsr *TokenStreamRewriter) InsertAfterToken(program_name string, token Token, text string){
- tsr.InsertAfter(program_name, token.GetTokenIndex(), text)
-}
-
-func (tsr* TokenStreamRewriter) InsertBefore(program_name string, index int, text string){
- var op RewriteOperation = NewInsertBeforeOp(index, text, tsr.tokens)
- rewrites := tsr.GetProgram(program_name)
- op.SetInstructionIndex(len(rewrites))
- tsr.AddToProgram(program_name, op)
-}
-
-func (tsr *TokenStreamRewriter) InsertBeforeDefault(index int, text string){
- tsr.InsertBefore(Default_Program_Name, index, text)
-}
-
-func (tsr *TokenStreamRewriter) InsertBeforeToken(program_name string,token Token, text string){
- tsr.InsertBefore(program_name, token.GetTokenIndex(), text)
-}
-
-func (tsr *TokenStreamRewriter) Replace(program_name string, from, to int, text string){
- if from > to || from < 0 || to < 0 || to >= tsr.tokens.Size(){
- panic(fmt.Sprintf("replace: range invalid: %d..%d(size=%d)",
- from, to, tsr.tokens.Size()))
- }
- var op RewriteOperation = NewReplaceOp(from, to, text, tsr.tokens)
- rewrites := tsr.GetProgram(program_name)
- op.SetInstructionIndex(len(rewrites))
- tsr.AddToProgram(program_name, op)
-}
-
-func (tsr *TokenStreamRewriter)ReplaceDefault(from, to int, text string) {
- tsr.Replace(Default_Program_Name, from, to, text)
-}
-
-func (tsr *TokenStreamRewriter)ReplaceDefaultPos(index int, text string){
- tsr.ReplaceDefault(index, index, text)
-}
-
-func (tsr *TokenStreamRewriter)ReplaceToken(program_name string, from, to Token, text string){
- tsr.Replace(program_name, from.GetTokenIndex(), to.GetTokenIndex(), text)
-}
-
-func (tsr *TokenStreamRewriter)ReplaceTokenDefault(from, to Token, text string){
- tsr.ReplaceToken(Default_Program_Name, from, to, text)
-}
-
-func (tsr *TokenStreamRewriter)ReplaceTokenDefaultPos(index Token, text string){
- tsr.ReplaceTokenDefault(index, index, text)
-}
-
-func (tsr *TokenStreamRewriter)Delete(program_name string, from, to int){
- tsr.Replace(program_name, from, to, "" )
-}
-
-func (tsr *TokenStreamRewriter)DeleteDefault(from, to int){
- tsr.Delete(Default_Program_Name, from, to)
-}
-
-func (tsr *TokenStreamRewriter)DeleteDefaultPos(index int){
- tsr.DeleteDefault(index,index)
-}
-
-func (tsr *TokenStreamRewriter)DeleteToken(program_name string, from, to Token) {
- tsr.ReplaceToken(program_name, from, to, "")
-}
-
-func (tsr *TokenStreamRewriter)DeleteTokenDefault(from,to Token){
- tsr.DeleteToken(Default_Program_Name, from, to)
-}
-
-func (tsr *TokenStreamRewriter)GetLastRewriteTokenIndex(program_name string)int {
- i, ok := tsr.last_rewrite_token_indexes[program_name]
- if !ok{
- return -1
- }
- return i
-}
-
-func (tsr *TokenStreamRewriter)GetLastRewriteTokenIndexDefault()int{
- return tsr.GetLastRewriteTokenIndex(Default_Program_Name)
-}
-
-func (tsr *TokenStreamRewriter)SetLastRewriteTokenIndex(program_name string, i int){
- tsr.last_rewrite_token_indexes[program_name] = i
-}
-
-func (tsr *TokenStreamRewriter)InitializeProgram(name string)[]RewriteOperation{
- is := make([]RewriteOperation, 0, Program_Init_Size)
- tsr.programs[name] = is
- return is
-}
-
-func (tsr *TokenStreamRewriter)AddToProgram(name string, op RewriteOperation){
- is := tsr.GetProgram(name)
- is = append(is, op)
- tsr.programs[name] = is
-}
-
-func (tsr *TokenStreamRewriter)GetProgram(name string) []RewriteOperation {
- is, ok := tsr.programs[name]
- if !ok{
- is = tsr.InitializeProgram(name)
- }
- return is
-}
-// Return the text from the original tokens altered per the
-// instructions given to this rewriter.
-func (tsr *TokenStreamRewriter)GetTextDefault() string{
- return tsr.GetText(
- Default_Program_Name,
- NewInterval(0, tsr.tokens.Size()-1))
-}
-// Return the text from the original tokens altered per the
-// instructions given to this rewriter.
-func (tsr *TokenStreamRewriter)GetText(program_name string, interval *Interval) string {
- rewrites := tsr.programs[program_name]
- start := interval.Start
- stop := interval.Stop
- // ensure start/end are in range
- stop = min(stop, tsr.tokens.Size()-1)
- start = max(start,0)
- if rewrites == nil || len(rewrites) == 0{
- return tsr.tokens.GetTextFromInterval(interval) // no instructions to execute
- }
- buf := bytes.Buffer{}
- // First, optimize instruction stream
- indexToOp := reduceToSingleOperationPerIndex(rewrites)
- // Walk buffer, executing instructions and emitting tokens
- for i:=start; i<=stop && i= tsr.tokens.Size()-1 {buf.WriteString(op.GetText())}
- }
- }
- return buf.String()
-}
-
-// We need to combine operations and report invalid operations (like
-// overlapping replaces that are not completed nested). Inserts to
-// same index need to be combined etc... Here are the cases:
-//
-// I.i.u I.j.v leave alone, nonoverlapping
-// I.i.u I.i.v combine: Iivu
-//
-// R.i-j.u R.x-y.v | i-j in x-y delete first R
-// R.i-j.u R.i-j.v delete first R
-// R.i-j.u R.x-y.v | x-y in i-j ERROR
-// R.i-j.u R.x-y.v | boundaries overlap ERROR
-//
-// Delete special case of replace (text==null):
-// D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right)
-//
-// I.i.u R.x-y.v | i in (x+1)-y delete I (since insert before
-// we're not deleting i)
-// I.i.u R.x-y.v | i not in (x+1)-y leave alone, nonoverlapping
-// R.x-y.v I.i.u | i in x-y ERROR
-// R.x-y.v I.x.u R.x-y.uv (combine, delete I)
-// R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping
-//
-// I.i.u = insert u before op @ index i
-// R.x-y.u = replace x-y indexed tokens with u
-//
-// First we need to examine replaces. For any replace op:
-//
-// 1. wipe out any insertions before op within that range.
-// 2. Drop any replace op before that is contained completely within
-// that range.
-// 3. Throw exception upon boundary overlap with any previous replace.
-//
-// Then we can deal with inserts:
-//
-// 1. for any inserts to same index, combine even if not adjacent.
-// 2. for any prior replace with same left boundary, combine this
-// insert with replace and delete this replace.
-// 3. throw exception if index in same range as previous replace
-//
-// Don't actually delete; make op null in list. Easier to walk list.
-// Later we can throw as we add to index → op map.
-//
-// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the
-// inserted stuff would be before the replace range. But, if you
-// add tokens in front of a method body '{' and then delete the method
-// body, I think the stuff before the '{' you added should disappear too.
-//
-// Return a map from token index to operation.
-//
-func reduceToSingleOperationPerIndex(rewrites []RewriteOperation) map[int]RewriteOperation{
- // WALK REPLACES
- for i:=0; i < len(rewrites); i++{
- op := rewrites[i]
- if op == nil{continue}
- rop, ok := op.(*ReplaceOp)
- if !ok{continue}
- // Wipe prior inserts within range
- for j:=0; j rop.index && iop.index <=rop.LastIndex{
- // delete insert as it's a no-op.
- rewrites[iop.instruction_index] = nil
- }
- }
- }
- // Drop any prior replaces contained within
- for j:=0; j=rop.index && prevop.LastIndex <= rop.LastIndex{
- // delete replace as it's a no-op.
- rewrites[prevop.instruction_index] = nil
- continue
- }
- // throw exception unless disjoint or identical
- disjoint := prevop.LastIndex < rop.index || prevop.index > rop.LastIndex
- // Delete special case of replace (text==null):
- // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right)
- if prevop.text == "" && rop.text == "" && !disjoint{
- rewrites[prevop.instruction_index] = nil
- rop.index = min(prevop.index, rop.index)
- rop.LastIndex = max(prevop.LastIndex, rop.LastIndex)
- println("new rop" + rop.String()) //TODO: remove console write, taken from Java version
- }else if !disjoint{
- panic("replace op boundaries of " + rop.String() + " overlap with previous " + prevop.String())
- }
- }
- }
- }
- // WALK INSERTS
- for i:=0; i < len(rewrites); i++ {
- op := rewrites[i]
- if op == nil{continue}
- //hack to replicate inheritance in composition
- _, iok := rewrites[i].(*InsertBeforeOp)
- _, aok := rewrites[i].(*InsertAfterOp)
- if !iok && !aok{continue}
- iop := rewrites[i]
- // combine current insert with prior if any at same index
- // deviating a bit from TokenStreamRewriter.java - hard to incorporate inheritance logic
- for j:=0; j= rop.index && iop.GetIndex() <= rop.LastIndex{
- panic("insert op "+iop.String()+" within boundaries of previous "+rop.String())
- }
- }
- }
- }
- m := map[int]RewriteOperation{}
- for i:=0; i < len(rewrites); i++{
- op := rewrites[i]
- if op == nil {continue}
- if _, ok := m[op.GetIndex()]; ok{
- panic("should only be one op per index")
- }
- m[op.GetIndex()] = op
- }
- return m
-}
-
-
-/*
- Quick fixing Go lack of overloads
- */
-
-func max(a,b int)int{
- if a>b{
- return a
- }else {
- return b
- }
-}
-func min(a,b int)int{
- if aThis is a one way link. It emanates from a state (usually via a list of
-// transitions) and has a target state.
-//
-// Since we never have to change the ATN transitions once we construct it,
-// the states. We'll use the term Edge for the DFA to distinguish them from
-// ATN transitions.
-
-type Transition interface {
- getTarget() ATNState
- setTarget(ATNState)
- getIsEpsilon() bool
- getLabel() *IntervalSet
- getSerializationType() int
- Matches(int, int, int) bool
-}
-
-type BaseTransition struct {
- target ATNState
- isEpsilon bool
- label int
- intervalSet *IntervalSet
- serializationType int
-}
-
-func NewBaseTransition(target ATNState) *BaseTransition {
-
- if target == nil {
- panic("target cannot be nil.")
- }
-
- t := new(BaseTransition)
-
- t.target = target
- // Are we epsilon, action, sempred?
- t.isEpsilon = false
- t.intervalSet = nil
-
- return t
-}
-
-func (t *BaseTransition) getTarget() ATNState {
- return t.target
-}
-
-func (t *BaseTransition) setTarget(s ATNState) {
- t.target = s
-}
-
-func (t *BaseTransition) getIsEpsilon() bool {
- return t.isEpsilon
-}
-
-func (t *BaseTransition) getLabel() *IntervalSet {
- return t.intervalSet
-}
-
-func (t *BaseTransition) getSerializationType() int {
- return t.serializationType
-}
-
-func (t *BaseTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- panic("Not implemented")
-}
-
-const (
- TransitionEPSILON = 1
- TransitionRANGE = 2
- TransitionRULE = 3
- TransitionPREDICATE = 4 // e.g., {isType(input.LT(1))}?
- TransitionATOM = 5
- TransitionACTION = 6
- TransitionSET = 7 // ~(A|B) or ~atom, wildcard, which convert to next 2
- TransitionNOTSET = 8
- TransitionWILDCARD = 9
- TransitionPRECEDENCE = 10
-)
-
-var TransitionserializationNames = []string{
- "INVALID",
- "EPSILON",
- "RANGE",
- "RULE",
- "PREDICATE",
- "ATOM",
- "ACTION",
- "SET",
- "NOT_SET",
- "WILDCARD",
- "PRECEDENCE",
-}
-
-//var TransitionserializationTypes struct {
-// EpsilonTransition int
-// RangeTransition int
-// RuleTransition int
-// PredicateTransition int
-// AtomTransition int
-// ActionTransition int
-// SetTransition int
-// NotSetTransition int
-// WildcardTransition int
-// PrecedencePredicateTransition int
-//}{
-// TransitionEPSILON,
-// TransitionRANGE,
-// TransitionRULE,
-// TransitionPREDICATE,
-// TransitionATOM,
-// TransitionACTION,
-// TransitionSET,
-// TransitionNOTSET,
-// TransitionWILDCARD,
-// TransitionPRECEDENCE
-//}
-
-// TODO: make all transitions sets? no, should remove set edges
-type AtomTransition struct {
- *BaseTransition
-}
-
-func NewAtomTransition(target ATNState, intervalSet int) *AtomTransition {
-
- t := new(AtomTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.label = intervalSet // The token type or character value or, signifies special intervalSet.
- t.intervalSet = t.makeLabel()
- t.serializationType = TransitionATOM
-
- return t
-}
-
-func (t *AtomTransition) makeLabel() *IntervalSet {
- s := NewIntervalSet()
- s.addOne(t.label)
- return s
-}
-
-func (t *AtomTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return t.label == symbol
-}
-
-func (t *AtomTransition) String() string {
- return strconv.Itoa(t.label)
-}
-
-type RuleTransition struct {
- *BaseTransition
-
- followState ATNState
- ruleIndex, precedence int
-}
-
-func NewRuleTransition(ruleStart ATNState, ruleIndex, precedence int, followState ATNState) *RuleTransition {
-
- t := new(RuleTransition)
- t.BaseTransition = NewBaseTransition(ruleStart)
-
- t.ruleIndex = ruleIndex
- t.precedence = precedence
- t.followState = followState
- t.serializationType = TransitionRULE
- t.isEpsilon = true
-
- return t
-}
-
-func (t *RuleTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return false
-}
-
-type EpsilonTransition struct {
- *BaseTransition
-
- outermostPrecedenceReturn int
-}
-
-func NewEpsilonTransition(target ATNState, outermostPrecedenceReturn int) *EpsilonTransition {
-
- t := new(EpsilonTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.serializationType = TransitionEPSILON
- t.isEpsilon = true
- t.outermostPrecedenceReturn = outermostPrecedenceReturn
- return t
-}
-
-func (t *EpsilonTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return false
-}
-
-func (t *EpsilonTransition) String() string {
- return "epsilon"
-}
-
-type RangeTransition struct {
- *BaseTransition
-
- start, stop int
-}
-
-func NewRangeTransition(target ATNState, start, stop int) *RangeTransition {
-
- t := new(RangeTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.serializationType = TransitionRANGE
- t.start = start
- t.stop = stop
- t.intervalSet = t.makeLabel()
- return t
-}
-
-func (t *RangeTransition) makeLabel() *IntervalSet {
- s := NewIntervalSet()
- s.addRange(t.start, t.stop)
- return s
-}
-
-func (t *RangeTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return symbol >= t.start && symbol <= t.stop
-}
-
-func (t *RangeTransition) String() string {
- return "'" + string(t.start) + "'..'" + string(t.stop) + "'"
-}
-
-type AbstractPredicateTransition interface {
- Transition
- IAbstractPredicateTransitionFoo()
-}
-
-type BaseAbstractPredicateTransition struct {
- *BaseTransition
-}
-
-func NewBasePredicateTransition(target ATNState) *BaseAbstractPredicateTransition {
-
- t := new(BaseAbstractPredicateTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- return t
-}
-
-func (a *BaseAbstractPredicateTransition) IAbstractPredicateTransitionFoo() {}
-
-type PredicateTransition struct {
- *BaseAbstractPredicateTransition
-
- isCtxDependent bool
- ruleIndex, predIndex int
-}
-
-func NewPredicateTransition(target ATNState, ruleIndex, predIndex int, isCtxDependent bool) *PredicateTransition {
-
- t := new(PredicateTransition)
- t.BaseAbstractPredicateTransition = NewBasePredicateTransition(target)
-
- t.serializationType = TransitionPREDICATE
- t.ruleIndex = ruleIndex
- t.predIndex = predIndex
- t.isCtxDependent = isCtxDependent // e.g., $i ref in pred
- t.isEpsilon = true
- return t
-}
-
-func (t *PredicateTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return false
-}
-
-func (t *PredicateTransition) getPredicate() *Predicate {
- return NewPredicate(t.ruleIndex, t.predIndex, t.isCtxDependent)
-}
-
-func (t *PredicateTransition) String() string {
- return "pred_" + strconv.Itoa(t.ruleIndex) + ":" + strconv.Itoa(t.predIndex)
-}
-
-type ActionTransition struct {
- *BaseTransition
-
- isCtxDependent bool
- ruleIndex, actionIndex, predIndex int
-}
-
-func NewActionTransition(target ATNState, ruleIndex, actionIndex int, isCtxDependent bool) *ActionTransition {
-
- t := new(ActionTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.serializationType = TransitionACTION
- t.ruleIndex = ruleIndex
- t.actionIndex = actionIndex
- t.isCtxDependent = isCtxDependent // e.g., $i ref in pred
- t.isEpsilon = true
- return t
-}
-
-func (t *ActionTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return false
-}
-
-func (t *ActionTransition) String() string {
- return "action_" + strconv.Itoa(t.ruleIndex) + ":" + strconv.Itoa(t.actionIndex)
-}
-
-type SetTransition struct {
- *BaseTransition
-}
-
-func NewSetTransition(target ATNState, set *IntervalSet) *SetTransition {
-
- t := new(SetTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.serializationType = TransitionSET
- if set != nil {
- t.intervalSet = set
- } else {
- t.intervalSet = NewIntervalSet()
- t.intervalSet.addOne(TokenInvalidType)
- }
-
- return t
-}
-
-func (t *SetTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return t.intervalSet.contains(symbol)
-}
-
-func (t *SetTransition) String() string {
- return t.intervalSet.String()
-}
-
-type NotSetTransition struct {
- *SetTransition
-}
-
-func NewNotSetTransition(target ATNState, set *IntervalSet) *NotSetTransition {
-
- t := new(NotSetTransition)
-
- t.SetTransition = NewSetTransition(target, set)
-
- t.serializationType = TransitionNOTSET
-
- return t
-}
-
-func (t *NotSetTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return symbol >= minVocabSymbol && symbol <= maxVocabSymbol && !t.intervalSet.contains(symbol)
-}
-
-func (t *NotSetTransition) String() string {
- return "~" + t.intervalSet.String()
-}
-
-type WildcardTransition struct {
- *BaseTransition
-}
-
-func NewWildcardTransition(target ATNState) *WildcardTransition {
-
- t := new(WildcardTransition)
- t.BaseTransition = NewBaseTransition(target)
-
- t.serializationType = TransitionWILDCARD
- return t
-}
-
-func (t *WildcardTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return symbol >= minVocabSymbol && symbol <= maxVocabSymbol
-}
-
-func (t *WildcardTransition) String() string {
- return "."
-}
-
-type PrecedencePredicateTransition struct {
- *BaseAbstractPredicateTransition
-
- precedence int
-}
-
-func NewPrecedencePredicateTransition(target ATNState, precedence int) *PrecedencePredicateTransition {
-
- t := new(PrecedencePredicateTransition)
- t.BaseAbstractPredicateTransition = NewBasePredicateTransition(target)
-
- t.serializationType = TransitionPRECEDENCE
- t.precedence = precedence
- t.isEpsilon = true
-
- return t
-}
-
-func (t *PrecedencePredicateTransition) Matches(symbol, minVocabSymbol, maxVocabSymbol int) bool {
- return false
-}
-
-func (t *PrecedencePredicateTransition) getPredicate() *PrecedencePredicate {
- return NewPrecedencePredicate(t.precedence)
-}
-
-func (t *PrecedencePredicateTransition) String() string {
- return fmt.Sprint(t.precedence) + " >= _p"
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tree.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tree.go
deleted file mode 100644
index ad0eabf..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/tree.go
+++ /dev/null
@@ -1,251 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-// The basic notion of a tree has a parent, a payload, and a list of children.
-// It is the most abstract interface for all the trees used by ANTLR.
-///
-
-var TreeInvalidInterval = NewInterval(-1, -2)
-
-type Tree interface {
- GetParent() Tree
- SetParent(Tree)
- GetPayload() interface{}
- GetChild(i int) Tree
- GetChildCount() int
- GetChildren() []Tree
-}
-
-type SyntaxTree interface {
- Tree
-
- GetSourceInterval() *Interval
-}
-
-type ParseTree interface {
- SyntaxTree
-
- Accept(Visitor ParseTreeVisitor) interface{}
- GetText() string
-
- ToStringTree([]string, Recognizer) string
-}
-
-type RuleNode interface {
- ParseTree
-
- GetRuleContext() RuleContext
- GetBaseRuleContext() *BaseRuleContext
-}
-
-type TerminalNode interface {
- ParseTree
-
- GetSymbol() Token
-}
-
-type ErrorNode interface {
- TerminalNode
-
- errorNode()
-}
-
-type ParseTreeVisitor interface {
- Visit(tree ParseTree) interface{}
- VisitChildren(node RuleNode) interface{}
- VisitTerminal(node TerminalNode) interface{}
- VisitErrorNode(node ErrorNode) interface{}
-}
-
-type BaseParseTreeVisitor struct{}
-
-var _ ParseTreeVisitor = &BaseParseTreeVisitor{}
-
-func (v *BaseParseTreeVisitor) Visit(tree ParseTree) interface{} { return nil }
-func (v *BaseParseTreeVisitor) VisitChildren(node RuleNode) interface{} { return nil }
-func (v *BaseParseTreeVisitor) VisitTerminal(node TerminalNode) interface{} { return nil }
-func (v *BaseParseTreeVisitor) VisitErrorNode(node ErrorNode) interface{} { return nil }
-
-// TODO
-//func (this ParseTreeVisitor) Visit(ctx) {
-// if (Utils.isArray(ctx)) {
-// self := this
-// return ctx.map(function(child) { return VisitAtom(self, child)})
-// } else {
-// return VisitAtom(this, ctx)
-// }
-//}
-//
-//func VisitAtom(Visitor, ctx) {
-// if (ctx.parser == nil) { //is terminal
-// return
-// }
-//
-// name := ctx.parser.ruleNames[ctx.ruleIndex]
-// funcName := "Visit" + Utils.titleCase(name)
-//
-// return Visitor[funcName](ctx)
-//}
-
-type ParseTreeListener interface {
- VisitTerminal(node TerminalNode)
- VisitErrorNode(node ErrorNode)
- EnterEveryRule(ctx ParserRuleContext)
- ExitEveryRule(ctx ParserRuleContext)
-}
-
-type BaseParseTreeListener struct{}
-
-var _ ParseTreeListener = &BaseParseTreeListener{}
-
-func (l *BaseParseTreeListener) VisitTerminal(node TerminalNode) {}
-func (l *BaseParseTreeListener) VisitErrorNode(node ErrorNode) {}
-func (l *BaseParseTreeListener) EnterEveryRule(ctx ParserRuleContext) {}
-func (l *BaseParseTreeListener) ExitEveryRule(ctx ParserRuleContext) {}
-
-type TerminalNodeImpl struct {
- parentCtx RuleContext
-
- symbol Token
-}
-
-var _ TerminalNode = &TerminalNodeImpl{}
-
-func NewTerminalNodeImpl(symbol Token) *TerminalNodeImpl {
- tn := new(TerminalNodeImpl)
-
- tn.parentCtx = nil
- tn.symbol = symbol
-
- return tn
-}
-
-func (t *TerminalNodeImpl) GetChild(i int) Tree {
- return nil
-}
-
-func (t *TerminalNodeImpl) GetChildren() []Tree {
- return nil
-}
-
-func (t *TerminalNodeImpl) SetChildren(tree []Tree) {
- panic("Cannot set children on terminal node")
-}
-
-func (t *TerminalNodeImpl) GetSymbol() Token {
- return t.symbol
-}
-
-func (t *TerminalNodeImpl) GetParent() Tree {
- return t.parentCtx
-}
-
-func (t *TerminalNodeImpl) SetParent(tree Tree) {
- t.parentCtx = tree.(RuleContext)
-}
-
-func (t *TerminalNodeImpl) GetPayload() interface{} {
- return t.symbol
-}
-
-func (t *TerminalNodeImpl) GetSourceInterval() *Interval {
- if t.symbol == nil {
- return TreeInvalidInterval
- }
- tokenIndex := t.symbol.GetTokenIndex()
- return NewInterval(tokenIndex, tokenIndex)
-}
-
-func (t *TerminalNodeImpl) GetChildCount() int {
- return 0
-}
-
-func (t *TerminalNodeImpl) Accept(v ParseTreeVisitor) interface{} {
- return v.VisitTerminal(t)
-}
-
-func (t *TerminalNodeImpl) GetText() string {
- return t.symbol.GetText()
-}
-
-func (t *TerminalNodeImpl) String() string {
- if t.symbol.GetTokenType() == TokenEOF {
- return ""
- }
-
- return t.symbol.GetText()
-}
-
-func (t *TerminalNodeImpl) ToStringTree(s []string, r Recognizer) string {
- return t.String()
-}
-
-// Represents a token that was consumed during reSynchronization
-// rather than during a valid Match operation. For example,
-// we will create this kind of a node during single token insertion
-// and deletion as well as during "consume until error recovery set"
-// upon no viable alternative exceptions.
-
-type ErrorNodeImpl struct {
- *TerminalNodeImpl
-}
-
-var _ ErrorNode = &ErrorNodeImpl{}
-
-func NewErrorNodeImpl(token Token) *ErrorNodeImpl {
- en := new(ErrorNodeImpl)
- en.TerminalNodeImpl = NewTerminalNodeImpl(token)
- return en
-}
-
-func (e *ErrorNodeImpl) errorNode() {}
-
-func (e *ErrorNodeImpl) Accept(v ParseTreeVisitor) interface{} {
- return v.VisitErrorNode(e)
-}
-
-type ParseTreeWalker struct {
-}
-
-func NewParseTreeWalker() *ParseTreeWalker {
- return new(ParseTreeWalker)
-}
-
-func (p *ParseTreeWalker) Walk(listener ParseTreeListener, t Tree) {
- switch tt := t.(type) {
- case ErrorNode:
- listener.VisitErrorNode(tt)
- case TerminalNode:
- listener.VisitTerminal(tt)
- default:
- p.EnterRule(listener, t.(RuleNode))
- for i := 0; i < t.GetChildCount(); i++ {
- child := t.GetChild(i)
- p.Walk(listener, child)
- }
- p.ExitRule(listener, t.(RuleNode))
- }
-}
-
-//
-// The discovery of a rule node, involves sending two events: the generic
-// {@link ParseTreeListener//EnterEveryRule} and a
-// {@link RuleContext}-specific event. First we trigger the generic and then
-// the rule specific. We to them in reverse order upon finishing the node.
-//
-func (p *ParseTreeWalker) EnterRule(listener ParseTreeListener, r RuleNode) {
- ctx := r.GetRuleContext().(ParserRuleContext)
- listener.EnterEveryRule(ctx)
- ctx.EnterRule(listener)
-}
-
-func (p *ParseTreeWalker) ExitRule(listener ParseTreeListener, r RuleNode) {
- ctx := r.GetRuleContext().(ParserRuleContext)
- ctx.ExitRule(listener)
- listener.ExitEveryRule(ctx)
-}
-
-var ParseTreeWalkerDefault = NewParseTreeWalker()
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/trees.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/trees.go
deleted file mode 100644
index 80144ec..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/trees.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import "fmt"
-
-/** A set of utility routines useful for all kinds of ANTLR trees. */
-
-// Print out a whole tree in LISP form. {@link //getNodeText} is used on the
-// node payloads to get the text for the nodes. Detect
-// parse trees and extract data appropriately.
-func TreesStringTree(tree Tree, ruleNames []string, recog Recognizer) string {
-
- if recog != nil {
- ruleNames = recog.GetRuleNames()
- }
-
- s := TreesGetNodeText(tree, ruleNames, nil)
-
- s = EscapeWhitespace(s, false)
- c := tree.GetChildCount()
- if c == 0 {
- return s
- }
- res := "(" + s + " "
- if c > 0 {
- s = TreesStringTree(tree.GetChild(0), ruleNames, nil)
- res += s
- }
- for i := 1; i < c; i++ {
- s = TreesStringTree(tree.GetChild(i), ruleNames, nil)
- res += (" " + s)
- }
- res += ")"
- return res
-}
-
-func TreesGetNodeText(t Tree, ruleNames []string, recog Parser) string {
- if recog != nil {
- ruleNames = recog.GetRuleNames()
- }
-
- if ruleNames != nil {
- switch t2 := t.(type) {
- case RuleNode:
- t3 := t2.GetRuleContext()
- altNumber := t3.GetAltNumber()
-
- if altNumber != ATNInvalidAltNumber {
- return fmt.Sprintf("%s:%d", ruleNames[t3.GetRuleIndex()], altNumber)
- }
- return ruleNames[t3.GetRuleIndex()]
- case ErrorNode:
- return fmt.Sprint(t2)
- case TerminalNode:
- if t2.GetSymbol() != nil {
- return t2.GetSymbol().GetText()
- }
- }
- }
-
- // no recog for rule names
- payload := t.GetPayload()
- if p2, ok := payload.(Token); ok {
- return p2.GetText()
- }
-
- return fmt.Sprint(t.GetPayload())
-}
-
-// Return ordered list of all children of this node
-func TreesGetChildren(t Tree) []Tree {
- list := make([]Tree, 0)
- for i := 0; i < t.GetChildCount(); i++ {
- list = append(list, t.GetChild(i))
- }
- return list
-}
-
-// Return a list of all ancestors of this node. The first node of
-// list is the root and the last is the parent of this node.
-//
-func TreesgetAncestors(t Tree) []Tree {
- ancestors := make([]Tree, 0)
- t = t.GetParent()
- for t != nil {
- f := []Tree{t}
- ancestors = append(f, ancestors...)
- t = t.GetParent()
- }
- return ancestors
-}
-
-func TreesFindAllTokenNodes(t ParseTree, ttype int) []ParseTree {
- return TreesfindAllNodes(t, ttype, true)
-}
-
-func TreesfindAllRuleNodes(t ParseTree, ruleIndex int) []ParseTree {
- return TreesfindAllNodes(t, ruleIndex, false)
-}
-
-func TreesfindAllNodes(t ParseTree, index int, findTokens bool) []ParseTree {
- nodes := make([]ParseTree, 0)
- treesFindAllNodes(t, index, findTokens, &nodes)
- return nodes
-}
-
-func treesFindAllNodes(t ParseTree, index int, findTokens bool, nodes *[]ParseTree) {
- // check this node (the root) first
-
- t2, ok := t.(TerminalNode)
- t3, ok2 := t.(ParserRuleContext)
-
- if findTokens && ok {
- if t2.GetSymbol().GetTokenType() == index {
- *nodes = append(*nodes, t2)
- }
- } else if !findTokens && ok2 {
- if t3.GetRuleIndex() == index {
- *nodes = append(*nodes, t3)
- }
- }
- // check children
- for i := 0; i < t.GetChildCount(); i++ {
- treesFindAllNodes(t.GetChild(i).(ParseTree), index, findTokens, nodes)
- }
-}
-
-func TreesDescendants(t ParseTree) []ParseTree {
- nodes := []ParseTree{t}
- for i := 0; i < t.GetChildCount(); i++ {
- nodes = append(nodes, TreesDescendants(t.GetChild(i).(ParseTree))...)
- }
- return nodes
-}
diff --git a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/utils.go b/vendor/github.com/antlr/antlr4/runtime/Go/antlr/utils.go
deleted file mode 100644
index bba2ffa..0000000
--- a/vendor/github.com/antlr/antlr4/runtime/Go/antlr/utils.go
+++ /dev/null
@@ -1,417 +0,0 @@
-// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
-// Use of this file is governed by the BSD 3-clause license that
-// can be found in the LICENSE.txt file in the project root.
-
-package antlr
-
-import (
- "bytes"
- "errors"
- "fmt"
- "sort"
- "strconv"
- "strings"
-)
-
-func intMin(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
-func intMax(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
-
-// A simple integer stack
-
-type IntStack []int
-
-var ErrEmptyStack = errors.New("Stack is empty")
-
-func (s *IntStack) Pop() (int, error) {
- l := len(*s) - 1
- if l < 0 {
- return 0, ErrEmptyStack
- }
- v := (*s)[l]
- *s = (*s)[0:l]
- return v, nil
-}
-
-func (s *IntStack) Push(e int) {
- *s = append(*s, e)
-}
-
-type Set struct {
- data map[int][]interface{}
- hashcodeFunction func(interface{}) int
- equalsFunction func(interface{}, interface{}) bool
-}
-
-func NewSet(
- hashcodeFunction func(interface{}) int,
- equalsFunction func(interface{}, interface{}) bool) *Set {
-
- s := new(Set)
-
- s.data = make(map[int][]interface{})
-
- if hashcodeFunction != nil {
- s.hashcodeFunction = hashcodeFunction
- } else {
- s.hashcodeFunction = standardHashFunction
- }
-
- if equalsFunction == nil {
- s.equalsFunction = standardEqualsFunction
- } else {
- s.equalsFunction = equalsFunction
- }
-
- return s
-}
-
-func standardEqualsFunction(a interface{}, b interface{}) bool {
-
- ac, oka := a.(comparable)
- bc, okb := b.(comparable)
-
- if !oka || !okb {
- panic("Not Comparable")
- }
-
- return ac.equals(bc)
-}
-
-func standardHashFunction(a interface{}) int {
- if h, ok := a.(hasher); ok {
- return h.hash()
- }
-
- panic("Not Hasher")
-}
-
-type hasher interface {
- hash() int
-}
-
-func (s *Set) length() int {
- return len(s.data)
-}
-
-func (s *Set) add(value interface{}) interface{} {
-
- key := s.hashcodeFunction(value)
-
- values := s.data[key]
-
- if s.data[key] != nil {
- for i := 0; i < len(values); i++ {
- if s.equalsFunction(value, values[i]) {
- return values[i]
- }
- }
-
- s.data[key] = append(s.data[key], value)
- return value
- }
-
- v := make([]interface{}, 1, 10)
- v[0] = value
- s.data[key] = v
-
- return value
-}
-
-func (s *Set) contains(value interface{}) bool {
-
- key := s.hashcodeFunction(value)
-
- values := s.data[key]
-
- if s.data[key] != nil {
- for i := 0; i < len(values); i++ {
- if s.equalsFunction(value, values[i]) {
- return true
- }
- }
- }
- return false
-}
-
-func (s *Set) values() []interface{} {
- var l []interface{}
-
- for _, v := range s.data {
- l = append(l, v...)
- }
-
- return l
-}
-
-func (s *Set) String() string {
- r := ""
-
- for _, av := range s.data {
- for _, v := range av {
- r += fmt.Sprint(v)
- }
- }
-
- return r
-}
-
-type BitSet struct {
- data map[int]bool
-}
-
-func NewBitSet() *BitSet {
- b := new(BitSet)
- b.data = make(map[int]bool)
- return b
-}
-
-func (b *BitSet) add(value int) {
- b.data[value] = true
-}
-
-func (b *BitSet) clear(index int) {
- delete(b.data, index)
-}
-
-func (b *BitSet) or(set *BitSet) {
- for k := range set.data {
- b.add(k)
- }
-}
-
-func (b *BitSet) remove(value int) {
- delete(b.data, value)
-}
-
-func (b *BitSet) contains(value int) bool {
- return b.data[value]
-}
-
-func (b *BitSet) values() []int {
- ks := make([]int, len(b.data))
- i := 0
- for k := range b.data {
- ks[i] = k
- i++
- }
- sort.Ints(ks)
- return ks
-}
-
-func (b *BitSet) minValue() int {
- min := 2147483647
-
- for k := range b.data {
- if k < min {
- min = k
- }
- }
-
- return min
-}
-
-func (b *BitSet) equals(other interface{}) bool {
- otherBitSet, ok := other.(*BitSet)
- if !ok {
- return false
- }
-
- if len(b.data) != len(otherBitSet.data) {
- return false
- }
-
- for k, v := range b.data {
- if otherBitSet.data[k] != v {
- return false
- }
- }
-
- return true
-}
-
-func (b *BitSet) length() int {
- return len(b.data)
-}
-
-func (b *BitSet) String() string {
- vals := b.values()
- valsS := make([]string, len(vals))
-
- for i, val := range vals {
- valsS[i] = strconv.Itoa(val)
- }
- return "{" + strings.Join(valsS, ", ") + "}"
-}
-
-type AltDict struct {
- data map[string]interface{}
-}
-
-func NewAltDict() *AltDict {
- d := new(AltDict)
- d.data = make(map[string]interface{})
- return d
-}
-
-func (a *AltDict) Get(key string) interface{} {
- key = "k-" + key
- return a.data[key]
-}
-
-func (a *AltDict) put(key string, value interface{}) {
- key = "k-" + key
- a.data[key] = value
-}
-
-func (a *AltDict) values() []interface{} {
- vs := make([]interface{}, len(a.data))
- i := 0
- for _, v := range a.data {
- vs[i] = v
- i++
- }
- return vs
-}
-
-type DoubleDict struct {
- data map[int]map[int]interface{}
-}
-
-func NewDoubleDict() *DoubleDict {
- dd := new(DoubleDict)
- dd.data = make(map[int]map[int]interface{})
- return dd
-}
-
-func (d *DoubleDict) Get(a, b int) interface{} {
- data := d.data[a]
-
- if data == nil {
- return nil
- }
-
- return data[b]
-}
-
-func (d *DoubleDict) set(a, b int, o interface{}) {
- data := d.data[a]
-
- if data == nil {
- data = make(map[int]interface{})
- d.data[a] = data
- }
-
- data[b] = o
-}
-
-func EscapeWhitespace(s string, escapeSpaces bool) string {
-
- s = strings.Replace(s, "\t", "\\t", -1)
- s = strings.Replace(s, "\n", "\\n", -1)
- s = strings.Replace(s, "\r", "\\r", -1)
- if escapeSpaces {
- s = strings.Replace(s, " ", "\u00B7", -1)
- }
- return s
-}
-
-func TerminalNodeToStringArray(sa []TerminalNode) []string {
- st := make([]string, len(sa))
-
- for i, s := range sa {
- st[i] = fmt.Sprintf("%v", s)
- }
-
- return st
-}
-
-func PrintArrayJavaStyle(sa []string) string {
- var buffer bytes.Buffer
-
- buffer.WriteString("[")
-
- for i, s := range sa {
- buffer.WriteString(s)
- if i != len(sa)-1 {
- buffer.WriteString(", ")
- }
- }
-
- buffer.WriteString("]")
-
- return buffer.String()
-}
-
-// The following routines were lifted from bits.rotate* available in Go 1.9.
-
-const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64
-
-// rotateLeft returns the value of x rotated left by (k mod UintSize) bits.
-// To rotate x right by k bits, call RotateLeft(x, -k).
-func rotateLeft(x uint, k int) uint {
- if uintSize == 32 {
- return uint(rotateLeft32(uint32(x), k))
- }
- return uint(rotateLeft64(uint64(x), k))
-}
-
-// rotateLeft32 returns the value of x rotated left by (k mod 32) bits.
-func rotateLeft32(x uint32, k int) uint32 {
- const n = 32
- s := uint(k) & (n - 1)
- return x<>(n-s)
-}
-
-// rotateLeft64 returns the value of x rotated left by (k mod 64) bits.
-func rotateLeft64(x uint64, k int) uint64 {
- const n = 64
- s := uint(k) & (n - 1)
- return x<>(n-s)
-}
-
-
-// murmur hash
-const (
- c1_32 uint = 0xCC9E2D51
- c2_32 uint = 0x1B873593
- n1_32 uint = 0xE6546B64
-)
-
-func murmurInit(seed int) int {
- return seed
-}
-
-func murmurUpdate(h1 int, k1 int) int {
- var k1u uint
- k1u = uint(k1) * c1_32
- k1u = rotateLeft(k1u, 15)
- k1u *= c2_32
-
- var h1u = uint(h1) ^ k1u
- k1u = rotateLeft(k1u, 13)
- h1u = h1u*5 + 0xe6546b64
- return int(h1u)
-}
-
-func murmurFinish(h1 int, numberOfWords int) int {
- var h1u uint = uint(h1)
- h1u ^= uint(numberOfWords * 4)
- h1u ^= h1u >> 16
- h1u *= uint(0x85ebca6b)
- h1u ^= h1u >> 13
- h1u *= 0xc2b2ae35
- h1u ^= h1u >> 16
-
- return int(h1u)
-}
diff --git a/vendor/github.com/bndr/gotabulate/.gitignore b/vendor/github.com/bndr/gotabulate/.gitignore
deleted file mode 100644
index 9fbcdd5..0000000
--- a/vendor/github.com/bndr/gotabulate/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-go-tabulate
diff --git a/vendor/github.com/bndr/gotabulate/.travis.yml b/vendor/github.com/bndr/gotabulate/.travis.yml
deleted file mode 100644
index 3c4bba3..0000000
--- a/vendor/github.com/bndr/gotabulate/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-
-go:
- - 1.2
- - 1.3
- - tip
-install:
- - go get github.com/stretchr/testify/assert
\ No newline at end of file
diff --git a/vendor/github.com/bndr/gotabulate/AUTHOR b/vendor/github.com/bndr/gotabulate/AUTHOR
deleted file mode 100644
index 9b0e546..0000000
--- a/vendor/github.com/bndr/gotabulate/AUTHOR
+++ /dev/null
@@ -1 +0,0 @@
-Vadim Kravcenko 2014
\ No newline at end of file
diff --git a/vendor/github.com/bndr/gotabulate/CHANGELOG b/vendor/github.com/bndr/gotabulate/CHANGELOG
deleted file mode 100644
index e69de29..0000000
diff --git a/vendor/github.com/bndr/gotabulate/CONTRIBUTORS b/vendor/github.com/bndr/gotabulate/CONTRIBUTORS
deleted file mode 100644
index fabe3e7..0000000
--- a/vendor/github.com/bndr/gotabulate/CONTRIBUTORS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Contributors git log --format='%aN <%aE>' | sort -uf
-Vadim Kravcenko
diff --git a/vendor/github.com/bndr/gotabulate/LICENSE b/vendor/github.com/bndr/gotabulate/LICENSE
deleted file mode 100644
index 5c304d1..0000000
--- a/vendor/github.com/bndr/gotabulate/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/bndr/gotabulate/README.md b/vendor/github.com/bndr/gotabulate/README.md
deleted file mode 100644
index 7256e47..0000000
--- a/vendor/github.com/bndr/gotabulate/README.md
+++ /dev/null
@@ -1,217 +0,0 @@
-# Gotabulate - Easily tabulate Data
-[](https://godoc.org/github.com/bndr/gotabulate)
-[](https://travis-ci.org/bndr/gotabulate)
-
-## Summary
-
-Go-Tabulate - Generic Go Library for easy tabulation of your data.
-
-## Installation
-
- go get github.com/bndr/gotabulate
-
-## Description
-
-Supported data types:
-- 2D Array of Int, Int64, Float64, String, interface{}
-- Map of String, interface{} (Keys will be used as header)
-
-## Usage
-```go
-
-// Create Some Fake Rows
-row_1 := []interface{}{"john", 20, "ready"}
-row_2 := []interface{}{"bndr", 23, "ready"}
-
-// Create an object from 2D interface array
-t := gotabulate.Create([][]interface{}{row_1, row_2})
-
-// Set the Headers (optional)
-t.SetHeaders([]string{"age", "status"})
-
-// Set the Empty String (optional)
-t.SetEmptyString("None")
-
-// Set Align (Optional)
-t.SetAlign("right")
-
-// Print the result: grid, or simple
-fmt.Println(t.Render("grid"))
-
-+---------+--------+-----------+
-| | age | status |
-+=========+========+===========+
-| john | 20 | ready |
-+---------+--------+-----------+
-| bndr | 23 | ready |
-+---------+--------+-----------+
-
-```
-
-## Example with String
-
-```
-// Some Strings
-string_1 := []string{"TV", "1000$", "Sold"}
-string_2 := []string{"PC", "50%", "on Hold"}
-
-// Create Object
-tabulate := gotabulate.Create([][]string{string_1, string_2})
-
-// Set Headers
-tabulate.SetHeaders([]string{"Type", "Cost", "Status"})
-
-// Render
-fmt.Println(tabulate.Render("simple"))
-
---------- ---------- ------------
- Type Cost Status
---------- ---------- ------------
- TV 1000$ Sold
-
- PC 50% on Hold
---------- ---------- ------------
-
-```
-
-## Example with String Wrapping
-
-```go
-tabulate := gotabulate.Create([][]string{[]string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis",
- "Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis", "zzLorem ipsum", " test", "test"}, []string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis",
- "Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis", "zzLorem ipsum", " test", "test"}, STRING_ARRAY, []string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis",
- "Vivamus laoreet vestibulum pretium. Nulla et ornare elit. Cum sociis natoque penatibus et magnis", "zzLorem ipsum", " test", "test"}, STRING_ARRAY})
-tabulate.SetHeaders([]string{"Header 1", "header 2", "header 3", "header 4"})
-// Set Max Cell Size
-tabulate.SetMaxCellSize(16)
-
-// Turn On String Wrapping
-tabulate.SetWrapStrings(true)
-
-// Render the table
-fmt.Println(tabulate.Render("grid"))
-
-+---------------------+---------------------+----------------+-------------+-------------+
-| | Header 1 | header 2 | header 3 | header 4 |
-+=====================+=====================+================+=============+=============+
-| Lorem ipsum dolo | Vivamus laoreet | Lorem ipsum | test | test |
-| r sit amet, cons | vestibulum preti | | | |
-| ectetur adipisci | um. Nulla et orn | | | |
-| ng elit. Vivamus | are elit. Cum so | | | |
-| laoreet vestibu | ciis natoque pen | | | |
-| lum pretium. Nul | atibus et magnis | | | |
-| la et ornare eli | | | | |
-| t. Cum sociis na | | | | |
-| toque penatibus | | | | |
-| et magnis | | | | |
-+---------------------+---------------------+----------------+-------------+-------------+
-| Lorem ipsum dolo | Vivamus laoreet | Lorem ipsum | test | test |
-| r sit amet, cons | vestibulum preti | | | |
-| ectetur adipisci | um. Nulla et orn | | | |
-| ng elit. Vivamus | are elit. Cum so | | | |
-| laoreet vestibu | ciis natoque pen | | | |
-| lum pretium. Nul | atibus et magnis | | | |
-| la et ornare eli | | | | |
-| t. Cum sociis na | | | | |
-| toque penatibus | | | | |
-| et magnis | | | | |
-+---------------------+---------------------+----------------+-------------+-------------+
-| test string | test string 2 | test | row | bndr |
-+---------------------+---------------------+----------------+-------------+-------------+
-| Lorem ipsum dolo | Vivamus laoreet | Lorem ipsum | test | test |
-| r sit amet, cons | vestibulum preti | | | |
-| ectetur adipisci | um. Nulla et orn | | | |
-| ng elit. Vivamus | are elit. Cum so | | | |
-| laoreet vestibu | ciis natoque pen | | | |
-| lum pretium. Nul | atibus et magnis | | | |
-| la et ornare eli | | | | |
-| t. Cum sociis na | | | | |
-| toque penatibus | | | | |
-| et magnis | | | | |
-+---------------------+---------------------+----------------+-------------+-------------+
-| test string | test string 2 | test | row | bndr |
-+---------------------+---------------------+----------------+-------------+-------------+
-
-```
-## Examples
-
-```
-t := gotabulate.Create([][]string{STRING_ARRAY, STRING_ARRAY})
-t.SetHeaders(HEADERS) // If not headers are set, the first row will be used.
-t.SetEmptyString("None") // Set what will be printed in the empty cell
-rendered_string := t.Render("simple") // Render() will return a string
-
-Simple Table
----------------------- ---------------------- ---------------------- ------------- -------------
- Header 1 Header 2 Header 3 Header 4 Header 5
----------------------- ---------------------- ---------------------- ------------- -------------
- test string test string 2 test row bndr
-
- test string test string 2 test row bndr
-
- 4th element empty 4th element empty 4th element empty None None
----------------------- ---------------------- ---------------------- ------------- -------------
-
-Grid Table (Align Right)
-+-------------+-------------+-------------+-------------+-------------+
-| Header 1 | Header 2 | Header 3 | Header 4 | Header 5 |
-+=============+=============+=============+=============+=============+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | None |
-+-------------+-------------+-------------+-------------+-------------+
-
-Padded Headers:
-+----------------------+----------------------+----------------------+-------------+-------------+
-| | Header 1 | header 2 | header 3 | header 4 |
-+======================+======================+======================+=============+=============+
-| test string | test string 2 | test | row | bndr |
-+----------------------+----------------------+----------------------+-------------+-------------+
-| test string | test string 2 | test | row | bndr |
-+----------------------+----------------------+----------------------+-------------+-------------+
-| 4th element empty | 4th element empty | 4th element empty | None | None |
-+----------------------+----------------------+----------------------+-------------+-------------+
-
-Align Center:
-+-------------+-------------+-------------+-------------+-------------+
-| Header 1 | Header 2 | Header 3 | Header 4 | Header 5 |
-+=============+=============+=============+=============+=============+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-
-Align Left:
-+-------------+-------------+-------------+-------------+-------------+
-| Header 1 | Header 2 | Header 3 | Header 4 | Header 5 |
-+=============+=============+=============+=============+=============+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-| 10.01 | 12.002 | -123.5 | 20.00005 | 1.01 |
-+-------------+-------------+-------------+-------------+-------------+
-```
-
-### Status
-Beta version. There may be edge cases that I have missed, so if your tables don't render properly please open up an issue.
-
-## Contribute
-
-All Contributions are welcome. The todo list is on the bottom of this README. Feel free to send a pull request.
-
-## License
-
-Apache License 2.0
-
-### TODO
-- Add more examples
-- Implement more data table formats
-
-### Acknowledgement
-
-Inspired by Python package https://pypi.python.org/pypi/tabulate
\ No newline at end of file
diff --git a/vendor/github.com/bndr/gotabulate/tabulate.go b/vendor/github.com/bndr/gotabulate/tabulate.go
deleted file mode 100644
index 6e19c5e..0000000
--- a/vendor/github.com/bndr/gotabulate/tabulate.go
+++ /dev/null
@@ -1,443 +0,0 @@
-package gotabulate
-
-import "fmt"
-import "bytes"
-import "math"
-
-// Basic Structure of TableFormat
-type TableFormat struct {
- LineTop Line
- LineBelowHeader Line
- LineBetweenRows Line
- LineBottom Line
- HeaderRow Row
- DataRow Row
- Padding int
- HeaderHide bool
- FitScreen bool
-}
-
-// Represents a Line
-type Line struct {
- begin string
- hline string
- sep string
- end string
-}
-
-// Represents a Row
-type Row struct {
- begin string
- sep string
- end string
-}
-
-// Table Formats that are available to the user
-// The user can define his own format, just by addind an entry to this map
-// and calling it with Render function e.g t.Render("customFormat")
-var TableFormats = map[string]TableFormat{
- "simple": TableFormat{
- LineTop: Line{"", "-", " ", ""},
- LineBelowHeader: Line{"", "-", " ", ""},
- LineBottom: Line{"", "-", " ", ""},
- HeaderRow: Row{"", " ", ""},
- DataRow: Row{"", " ", ""},
- Padding: 1,
- },
- "plain": TableFormat{
- HeaderRow: Row{"", " ", ""},
- DataRow: Row{"", " ", ""},
- Padding: 1,
- },
- "grid": TableFormat{
- LineTop: Line{"+", "-", "+", "+"},
- LineBelowHeader: Line{"+", "=", "+", "+"},
- LineBetweenRows: Line{"+", "-", "+", "+"},
- LineBottom: Line{"+", "-", "+", "+"},
- HeaderRow: Row{"|", "|", "|"},
- DataRow: Row{"|", "|", "|"},
- Padding: 1,
- },
-}
-
-// Minimum padding that will be applied
-var MIN_PADDING = 5
-
-// Main Tabulate structure
-type Tabulate struct {
- Data []*TabulateRow
- Headers []string
- FloatFormat byte
- TableFormat TableFormat
- Align string
- EmptyVar string
- HideLines []string
- MaxSize int
- WrapStrings bool
-}
-
-// Represents normalized tabulate Row
-type TabulateRow struct {
- Elements []string
- Continuos bool
- Extra bool
-}
-
-// Add padding to each cell
-func (t *Tabulate) padRow(arr []string, padding int) []string {
- if len(arr) < 1 {
- return arr
- }
- padded := make([]string, len(arr))
- for index, el := range arr {
- var buffer bytes.Buffer
- // Pad left
- for i := 0; i < padding; i++ {
- buffer.WriteString(" ")
- }
-
- buffer.WriteString(el)
-
- // Pad Right
- for i := 0; i < padding; i++ {
- buffer.WriteString(" ")
- }
-
- padded[index] = buffer.String()
- }
- return padded
-}
-
-// Align right (Add padding left)
-func (t *Tabulate) padLeft(width int, str string) string {
- var buffer bytes.Buffer
- // Pad left
- padding := width - len(str)
- for i := 0; i < padding; i++ {
- buffer.WriteString(" ")
- }
- buffer.WriteString(str)
- return buffer.String()
-}
-
-// Align Left (Add padding right)
-func (t *Tabulate) padRight(width int, str string) string {
- var buffer bytes.Buffer
- padding := width - len(str)
-
- buffer.WriteString(str)
-
- // Add Padding right
- for i := 0; i < padding; i++ {
- buffer.WriteString(" ")
- }
- return buffer.String()
-}
-
-// Center the element in the cell
-func (t *Tabulate) padCenter(width int, str string) string {
- var buffer bytes.Buffer
- length := len(str)
-
- padding := int(math.Ceil(float64((width - length)) / 2.0))
-
- // Add padding left
- for i := 0; i < padding; i++ {
- buffer.WriteString(" ")
- }
-
- // Write string
- buffer.WriteString(str)
-
- // Calculate how much space is left
- current := (width - len(buffer.String()))
-
- // Add padding right
- for i := 0; i < current; i++ {
- buffer.WriteString(" ")
- }
- return buffer.String()
-}
-
-// Build Line based on padded_widths from t.GetWidths()
-func (t *Tabulate) buildLine(padded_widths []int, padding []int, l Line) string {
- cells := make([]string, len(padded_widths))
-
- for i, _ := range cells {
- var buffer bytes.Buffer
- for j := 0; j < padding[i]+MIN_PADDING; j++ {
- buffer.WriteString(l.hline)
- }
- cells[i] = buffer.String()
- }
- var buffer bytes.Buffer
-
- // Print begin
- buffer.WriteString(l.begin)
-
- // Print contents
- for i := 0; i < len(cells); i++ {
- if i != len(cells)-1 {
- buffer.WriteString(cells[i] + l.sep)
- } else {
- buffer.WriteString(cells[i])
- }
- }
-
- // Print end
- buffer.WriteString(l.end)
- return buffer.String()
-}
-
-// Build Row based on padded_widths from t.GetWidths()
-func (t *Tabulate) buildRow(elements []string, padded_widths []int, paddings []int, d Row) string {
-
- var buffer bytes.Buffer
- buffer.WriteString(d.begin)
- padFunc := t.getAlignFunc()
- // Print contents
- for i := 0; i < len(padded_widths); i++ {
- output := ""
- if len(elements) > i {
- output = padFunc(padded_widths[i], elements[i])
- } else {
- output = padFunc(padded_widths[i], t.EmptyVar)
- }
- buffer.WriteString(output)
- if i != len(padded_widths)-1 {
- buffer.WriteString(d.sep)
- }
- }
- // Print end
- buffer.WriteString(d.end)
-
- return buffer.String()
-}
-
-// Render the data table
-func (t *Tabulate) Render(format ...interface{}) string {
- var lines []string
-
- // If headers are set use them, otherwise pop the first row
- if len(t.Headers) < 1 {
- t.Headers, t.Data = t.Data[0].Elements, t.Data[1:]
- }
-
- // Use the format that was passed as parameter, otherwise
- // use the format defined in the struct
- if len(format) > 0 {
- t.TableFormat = TableFormats[format[0].(string)]
- }
-
- // If Wrap Strings is set to True,then break up the string to multiple cells
- if t.WrapStrings {
- t.Data = t.wrapCellData()
- }
-
- // Check if Data is present
- if len(t.Data) < 1 {
- panic("No Data specified")
- }
-
- if len(t.Headers) < len(t.Data[0].Elements) {
- diff := len(t.Data[0].Elements) - len(t.Headers)
- padded_header := make([]string, diff)
- for _, e := range t.Headers {
- padded_header = append(padded_header, e)
- }
- t.Headers = padded_header
- }
-
- // Get Column widths for all columns
- cols := t.getWidths(t.Headers, t.Data)
-
- padded_widths := make([]int, len(cols))
- for i, _ := range padded_widths {
- padded_widths[i] = cols[i] + MIN_PADDING*t.TableFormat.Padding
- }
-
- // Start appending lines
-
- // Append top line if not hidden
- if !inSlice("top", t.HideLines) {
- lines = append(lines, t.buildLine(padded_widths, cols, t.TableFormat.LineTop))
- }
-
- // Add Header
- lines = append(lines, t.buildRow(t.padRow(t.Headers, t.TableFormat.Padding), padded_widths, cols, t.TableFormat.HeaderRow))
-
- // Add Line Below Header if not hidden
- if !inSlice("belowheader", t.HideLines) {
- lines = append(lines, t.buildLine(padded_widths, cols, t.TableFormat.LineBelowHeader))
- }
-
- // Add Data Rows
- for index, element := range t.Data {
- lines = append(lines, t.buildRow(t.padRow(element.Elements, t.TableFormat.Padding), padded_widths, cols, t.TableFormat.DataRow))
- if index < len(t.Data)-1 {
- if element.Continuos != true {
- lines = append(lines, t.buildLine(padded_widths, cols, t.TableFormat.LineBetweenRows))
- }
- }
- }
-
- if !inSlice("bottomLine", t.HideLines) {
- lines = append(lines, t.buildLine(padded_widths, cols, t.TableFormat.LineBottom))
- }
-
- // Join lines
- var buffer bytes.Buffer
- for _, line := range lines {
- buffer.WriteString(line + "\n")
- }
-
- return buffer.String()
-}
-
-// Calculate the max column width for each element
-func (t *Tabulate) getWidths(headers []string, data []*TabulateRow) []int {
- widths := make([]int, len(headers))
- current_max := len(t.EmptyVar)
- for i := 0; i < len(headers); i++ {
- current_max = len(headers[i])
- for _, item := range data {
- if len(item.Elements) > i && len(widths) > i {
- element := item.Elements[i]
- if len(element) > current_max {
- widths[i] = len(element)
- current_max = len(element)
- } else {
- widths[i] = current_max
- }
- }
- }
- }
-
- return widths
-}
-
-// Set Headers of the table
-// If Headers count is less than the data row count, the headers will be padded to the right
-func (t *Tabulate) SetHeaders(headers []string) *Tabulate {
- t.Headers = headers
- return t
-}
-
-// Set Float Formatting
-// will be used in strconv.FormatFloat(element, format, -1, 64)
-func (t *Tabulate) SetFloatFormat(format byte) *Tabulate {
- t.FloatFormat = format
- return t
-}
-
-// Set Align Type, Available options: left, right, center
-func (t *Tabulate) SetAlign(align string) {
- t.Align = align
-}
-
-// Select the padding function based on the align type
-func (t *Tabulate) getAlignFunc() func(int, string) string {
- if len(t.Align) < 1 || t.Align == "right" {
- return t.padLeft
- } else if t.Align == "left" {
- return t.padRight
- } else {
- return t.padCenter
- }
-}
-
-// Set how an empty cell will be represented
-func (t *Tabulate) SetEmptyString(empty string) {
- t.EmptyVar = empty + " "
-}
-
-// Set which lines to hide.
-// Can be:
-// top - Top line of the table,
-// belowheader - Line below the header,
-// bottom - Bottom line of the table
-func (t *Tabulate) SetHideLines(hide []string) {
- t.HideLines = hide
-}
-
-func (t *Tabulate) SetWrapStrings(wrap bool) {
- t.WrapStrings = wrap
-}
-
-// Sets the maximum size of cell
-// If WrapStrings is set to true, then the string inside
-// the cell will be split up into multiple cell
-func (t *Tabulate) SetMaxCellSize(max int) {
- t.MaxSize = max
-}
-
-// If string size is larger than t.MaxSize, then split it to multiple cells (downwards)
-func (t *Tabulate) wrapCellData() []*TabulateRow {
- var arr []*TabulateRow
- next := t.Data[0]
- for index := 0; index <= len(t.Data); index++ {
- elements := next.Elements
- new_elements := make([]string, len(elements))
-
- for i, e := range elements {
- if len(e) > t.MaxSize {
- new_elements[i] = e[t.MaxSize:]
- elements[i] = e[:t.MaxSize]
- next.Continuos = true
- }
- }
-
- if next.Continuos {
- arr = append(arr, next)
- next = &TabulateRow{Elements: new_elements, Extra: true}
- index--
- } else if next.Extra && index+1 < len(t.Data) {
- arr = append(arr, next)
- next = t.Data[index+1]
- } else if index+1 < len(t.Data) {
- arr = append(arr, next)
- next = t.Data[index+1]
- } else if index >= len(t.Data) {
- arr = append(arr, next)
- }
-
- }
- return arr
-}
-
-// Create a new Tabulate Object
-// Accepts 2D String Array, 2D Int Array, 2D Int64 Array,
-// 2D Bool Array, 2D Float64 Array, 2D interface{} Array,
-// Map map[strig]string, Map map[string]interface{},
-func Create(data interface{}) *Tabulate {
- t := &Tabulate{FloatFormat: 'f', MaxSize: 30}
-
- switch v := data.(type) {
- case [][]string:
- t.Data = createFromString(data.([][]string))
- case [][]int32:
- t.Data = createFromInt32(data.([][]int32))
- case [][]int64:
- t.Data = createFromInt64(data.([][]int64))
- case [][]int:
- t.Data = createFromInt(data.([][]int))
- case [][]bool:
- t.Data = createFromBool(data.([][]bool))
- case [][]float64:
- t.Data = createFromFloat64(data.([][]float64), t.FloatFormat)
- case [][]interface{}:
- t.Data = createFromMixed(data.([][]interface{}), t.FloatFormat)
- case []string:
- t.Data = createFromString([][]string{data.([]string)})
- case []interface{}:
- t.Data = createFromMixed([][]interface{}{data.([]interface{})}, t.FloatFormat)
- case map[string][]interface{}:
- t.Headers, t.Data = createFromMapMixed(data.(map[string][]interface{}), t.FloatFormat)
- case map[string][]string:
- t.Headers, t.Data = createFromMapString(data.(map[string][]string))
- default:
- fmt.Println(v)
- }
-
- return t
-}
diff --git a/vendor/github.com/bndr/gotabulate/utils.go b/vendor/github.com/bndr/gotabulate/utils.go
deleted file mode 100644
index bc65c0f..0000000
--- a/vendor/github.com/bndr/gotabulate/utils.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package gotabulate
-
-import "strconv"
-import "fmt"
-
-// Create normalized Array from strings
-func createFromString(data [][]string) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
-
- for index, el := range data {
- rows[index] = &TabulateRow{Elements: el}
- }
- return rows
-}
-
-// Create normalized array of rows from mixed data (interface{})
-func createFromMixed(data [][]interface{}, format byte) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, element := range data {
- normalized := make([]string, len(element))
- for index, el := range element {
- switch el.(type) {
- case int32:
- quoted := strconv.QuoteRuneToASCII(el.(int32))
- normalized[index] = quoted[1 : len(quoted)-1]
- case int:
- normalized[index] = strconv.Itoa(el.(int))
- case int64:
- normalized[index] = strconv.FormatInt(el.(int64), 10)
- case bool:
- normalized[index] = strconv.FormatBool(el.(bool))
- case float64:
- normalized[index] = strconv.FormatFloat(el.(float64), format, -1, 64)
- case uint64:
- normalized[index] = strconv.FormatUint(el.(uint64), 10)
- default:
- normalized[index] = fmt.Sprintf("%s", el)
- }
- }
- rows[index_1] = &TabulateRow{Elements: normalized}
- }
- return rows
-}
-
-// Create normalized array from ints
-func createFromInt(data [][]int) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, arr := range data {
- row := make([]string, len(arr))
- for index, el := range arr {
- row[index] = strconv.Itoa(el)
- }
- rows[index_1] = &TabulateRow{Elements: row}
- }
- return rows
-}
-
-// Create normalized array from float64
-func createFromFloat64(data [][]float64, format byte) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, arr := range data {
- row := make([]string, len(arr))
- for index, el := range arr {
- row[index] = strconv.FormatFloat(el, format, -1, 64)
- }
- rows[index_1] = &TabulateRow{Elements: row}
- }
- return rows
-}
-
-// Create normalized array from ints32
-func createFromInt32(data [][]int32) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, arr := range data {
- row := make([]string, len(arr))
- for index, el := range arr {
- quoted := strconv.QuoteRuneToASCII(el)
- row[index] = quoted[1 : len(quoted)-1]
- }
- rows[index_1] = &TabulateRow{Elements: row}
- }
- return rows
-}
-
-// Create normalized array from ints64
-func createFromInt64(data [][]int64) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, arr := range data {
- row := make([]string, len(arr))
- for index, el := range arr {
- row[index] = strconv.FormatInt(el, 10)
- }
- rows[index_1] = &TabulateRow{Elements: row}
- }
- return rows
-}
-
-// Create normalized array from bools
-func createFromBool(data [][]bool) []*TabulateRow {
- rows := make([]*TabulateRow, len(data))
- for index_1, arr := range data {
- row := make([]string, len(arr))
- for index, el := range arr {
- row[index] = strconv.FormatBool(el)
- }
- rows[index_1] = &TabulateRow{Elements: row}
- }
- return rows
-}
-
-// Create normalized array from a map of mixed elements (interface{})
-// Keys will be used as header
-func createFromMapMixed(data map[string][]interface{}, format byte) (headers []string, tData []*TabulateRow) {
-
- var dataslice [][]interface{}
- for key, value := range data {
- headers = append(headers, key)
- dataslice = append(dataslice, value)
- }
- return headers, createFromMixed(dataslice, format)
-}
-
-// Create normalized array from Map of strings
-// Keys will be used as header
-func createFromMapString(data map[string][]string) (headers []string, tData []*TabulateRow) {
- var dataslice [][]string
- for key, value := range data {
- headers = append(headers, key)
- dataslice = append(dataslice, value)
- }
- return headers, createFromString(dataslice)
-}
-
-// Check if element is present in a slice.
-func inSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/caibirdme/yql/.gitignore b/vendor/github.com/caibirdme/yql/.gitignore
deleted file mode 100644
index 60b4e72..0000000
--- a/vendor/github.com/caibirdme/yql/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-.antlr
-debug.test
-.vscode
\ No newline at end of file
diff --git a/vendor/github.com/caibirdme/yql/.travis.yml b/vendor/github.com/caibirdme/yql/.travis.yml
deleted file mode 100644
index 3118a0b..0000000
--- a/vendor/github.com/caibirdme/yql/.travis.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-language: go
-go:
- - 1.8.x
- - 1.9.x
-script: go get "github.com/stretchr/testify/assert" && go test .
\ No newline at end of file
diff --git a/vendor/github.com/caibirdme/yql/LICENSE b/vendor/github.com/caibirdme/yql/LICENSE
deleted file mode 100644
index 7af5aaa..0000000
--- a/vendor/github.com/caibirdme/yql/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2019 Deen
-
-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.
diff --git a/vendor/github.com/caibirdme/yql/README.md b/vendor/github.com/caibirdme/yql/README.md
deleted file mode 100644
index 1fd2313..0000000
--- a/vendor/github.com/caibirdme/yql/README.md
+++ /dev/null
@@ -1,189 +0,0 @@
-### YQL(Yet another-Query-Language)
-[](https://www.travis-ci.org/caibirdme/yql)
-[](https://godoc.org/github.com/caibirdme/yql)
-
-
-YQL is very similar with the `where` part of sql. You can see it as another sql which also support comparison between two sets. YQL have little concepts thus you can use it well short after reading the examples.Though it's designed for rule engine, it can be widely used in your code logic.
-
-### Install
-`go get github.com/caibirdme/yql`
-
-### Exmaple
-See more examples in the `yql_test.go` and godoc.
-
-``` go
- rawYQL := `name='deen' and age>=23 and (hobby in ('soccer', 'swim') or score>90))`
- result, _ := yql.Match(rawYQL, map[string]interface{}{
- "name": "deen",
- "age": int64(23),
- "hobby": "basketball",
- "score": int64(100),
- })
- fmt.Println(result)
- rawYQL = `score ∩ (7,1,9,5,3)`
- result, _ = yql.Match(rawYQL, map[string]interface{}{
- "score": []int64{3, 100, 200},
- })
- fmt.Println(result)
- rawYQL = `score in (7,1,9,5,3)`
- result, _ = yql.Match(rawYQL, map[string]interface{}{
- "score": []int64{3, 5, 2},
- })
- fmt.Println(result)
- rawYQL = `score.sum() > 10`
- result, _ = yql.Match(rawYQL, map[string]interface{}{
- "score": []int{1, 2, 3, 4, 5},
- })
- fmt.Println(result)
- //Output:
- //true
- //true
- //false
- //true
-```
-
-And In most cases, you can use `Rule` to cache the AST and then use `Match` to get the result, which could avoid hundreds of thousands of repeated parsing process.
-
-```go
- rawYQL := `name='deen' and age>=23 and (hobby in ('soccer', 'swim') or score>90)`
- ruler,_ := yql.Rule(rawYQL)
-
- result, _ := ruler.Match(map[string]interface{}{
- "name": "deen",
- "age": 23,
- "hobby": "basketball",
- "score": int64(100),
- })
- fmt.Println(result)
- result, _ = ruler.Match(map[string]interface{}{
- "name": "deen",
- "age": 23,
- "hobby": "basketball",
- "score": int64(90),
- })
- fmt.Println(result)
- //Output:
- //true
- //false
-```
-
-Though the to be matched data is the type of `map[string]interface{}`, there're only 5 types supported:
-* int
-* int64
-* float64
-* string
-* bool
-
-### Helpers
-In `score.sum() > 10`, `sum` is a helper function which adds up all the numbers in score, which also means the type of score must be one of the []int,[]int64 or []float64.
-
-This repo is in the early stage, so now there are just a few helpers, feel free to create an issue about your needs. Supported helpers are listed below:
-* sum: ...
-* count: return the length of a slice or 1 if not a slice
-* avg: return the average number of a slice(`float64(total)/float64(len(slice))`)
-* max: return the maximum number in a slice
-* min: return the minimum number in a slice
-
-### Usage scenario
-Obviously, it's easy to use in rule engine.
-```go
-var handlers = map[int]func(map[string]interface{}){
- 1: sendEmail,
- 2: sendMessage,
- 3: alertBoss,
-}
-
-data := resolvePostParamsFromRequest(request)
-rules := getRulesFromDB(sql)
-
-for _,rule := range rules {
- if success,_ := yql.Match(rule.YQL, data); success {
- handler := handlers[rule.ID]
- handler(data)
- break
- }
-}
-```
-
-Also, it can be used in your daily work, which could significantly reduce the deeply embebbed `if else` statements:
-```go
-func isVIP(user User) bool {
- rule := fmt.Sprintf("monthly_vip=true and now<%s or eternal_vip=1 or ab_test!=false", user.ExpireTime)
- ok,_ := yql.Match(rule, map[string]interface{}{
- "monthly_vip": user.IsMonthlyVIP,
- "now": time.Now().Unix(),
- "eternal_vip": user.EternalFlag,
- "ab_test": isABTestMatched(user),
- })
- return ok
-}
-```
-
-Even, you can use `json.Marshal` to generate the map[string]interface{} if you don't want to write it manually. Make sure the structure tag should be same as the name in rawYQL.
-
-### Syntax
-See [grammar file](./internal/grammar/Yql.g4)
-
-### Compatibility promise
-The API `Match`is stable now. Its grammar won't change any more, and what I only will do next is to optimize, speed up and add more helpers if needed.
-
-
-### Further Trial
-Though it's kinder difficult to create a robust new Go compiler, there're still some interesting things could do. For example, bringing lambda function in Go which maybe look like:
-```go
-var scores = []int{1,2,3,4,5,6,7,8,9,10}
-newSlice := yql.Filter(`(v) => v % 2 == 0`).Map(`(v) => v*v`).Call(scores).Interface()
-//[]int{4,16,36,64,100}
-```
-If the lambda function won't change all time, it can be cached like opcode, which is as fast as the compiled code. And in most cases, who care?(pythoner?)
-
-It's not easy but interesting, isn't it? Welcome to join me, open some issues and talk about your ideas with me. Maybe one day it can become a pre-compile tool like [babel](http://babeljs.io/) in javascript.
-
-#### Attention
-`Lambda expression` now is in its very early stage, **DO NOT USE IT IN PRODUCTION**.
-
-You can take a quick preview in [test case](/lambda/lambda_test.go)
-
-```go
-type Student struct {
- Age int
- Name string
-}
-
-var students = []Student{
- Student{
- Name: "deen",
- Age: 24,
- },
- Student{
- Name: "bob",
- Age: 22,
- },
- Student{
- Name: "alice",
- Age: 23,
- },
- Student{
- Name: "tom",
- Age: 25,
- },
- Student{
- Name: "jerry",
- Age: 20,
- },
-}
-
-t = yql.Filter(`(v) => v.Age > 23 || v.Name == "alice"`).Call(students).Interface()
-res,_ := t.([]Student)
-// res: Student{"deen",24} Student{"alice", 23} Student{"tom", 25}
-```
-
-Chainable
-```go
-dst := []int{1, 2, 3, 4, 5, 6, 7}
-r := Filter(`(v) => v > 3 && v <= 7`).Map(`(v) => v << 2`).Filter(`(v) => v % 8 == 0`).Call(dst)
-s, err := r.Interface()
-ass := assert.New(t)
-ass.NoError(err)
-ass.Equal([]int{16, 24}, s)
-```
\ No newline at end of file
diff --git a/vendor/github.com/caibirdme/yql/cmp.go b/vendor/github.com/caibirdme/yql/cmp.go
deleted file mode 100644
index 45dfc17..0000000
--- a/vendor/github.com/caibirdme/yql/cmp.go
+++ /dev/null
@@ -1,343 +0,0 @@
-package yql
-
-import (
- "math"
- "sort"
- "strconv"
-)
-
-const (
- opEqual = "="
- opNotEqual = "!="
- opLarger = ">"
- opLargerEqual = ">="
- opLess = "<"
- opLessEqual = "<="
- opInter = "∩"
- opNotInter = "!∩"
- opIn = "in"
- opNotIn = "!in"
-)
-
-const (
- epsilon = float64(1e-10)
-)
-
-func cmpInt(actual, expect int64, op string) bool {
- switch op {
- case opEqual,opIn:
- return actual == expect
- case opNotEqual,opNotIn:
- return actual != expect
- case opLarger:
- return actual > expect
- case opLargerEqual:
- return actual >= expect
- case opLess:
- return actual < expect
- case opLessEqual:
- return actual <= expect
- default:
- return false
- }
-}
-
-func cmpFloat(actual, expect float64, op string) bool {
- switch op {
- case opEqual:
- return floatEqual(actual, expect)
- case opNotEqual:
- return !floatEqual(actual, expect)
- case opLarger:
- return actual > expect
- case opLargerEqual:
- return !(actual < expect)
- case opLess:
- return actual < expect
- case opLessEqual:
- return floatLessEqual(actual, expect)
- default:
- return false
- }
-}
-
-func cmpStr(actual, expect string, op string) bool {
- switch op {
- case opEqual,opIn:
- return actual == expect
- case opNotEqual,opNotIn:
- return actual != expect
- case opLarger:
- return actual > expect
- case opLargerEqual:
- return actual >= expect
- case opLess:
- return actual < expect
- case opLessEqual:
- return actual <= expect
- default:
- return false
- }
-}
-
-func cmpBool(actual, expect bool, op string) bool {
- switch op {
- case opEqual:
- return actual == expect
- case opNotEqual:
- return actual != expect
- default:
- return false
- }
-}
-
-func compareSet(actual interface{}, expect []string, op string) bool {
- switch op {
- case opEqual, opNotEqual, opInter, opNotInter, opIn, opNotIn:
- default:
- return false
- }
- switch actualArr := actual.(type) {
- case int:
- return cmpIntSet([]int64{int64(actualArr)}, expect, op)
- case int64:
- return cmpIntSet([]int64{actualArr}, expect, op)
- case float64:
- return cmpFloatSet([]float64{actualArr}, expect, op)
- case string:
- return cmpStringSet([]string{actualArr}, expect, op)
- case []int:
- return cmpIntSet(intArr2i64Arr(actualArr), expect, op)
- case []int64:
- return cmpIntSet(actualArr, expect, op)
- case []float64:
- return cmpFloatSet(actualArr, expect, op)
- case []string:
- return cmpStringSet(actualArr, expect, op)
- default:
- return false
- }
-}
-
-func intArr2i64Arr(arr []int) []int64 {
- length := len(arr)
- if length == 0 {
- return nil
- }
- res := make([]int64, 0, length)
- for _, v := range arr {
- res = append(res, int64(v))
- }
- return res
-}
-
-var intSetCmpFunc = map[string]func([]int64, []int64) bool{
- opInter: intSetInter,
- opNotInter: intSetNotInter,
- opIn: intSetBelong,
- opNotIn: intSetNotBelong,
-}
-
-func cmpIntSet(actualVals []int64, expectVals []string, op string) bool {
- expectArr := make([]int64, 0, len(expectVals))
- for _, expect := range expectVals {
- v, err := strconv.ParseInt(removeQuote(expect), 10, 64)
- if nil != err {
- return false
- }
- expectArr = append(expectArr, v)
- }
- cmp, ok := intSetCmpFunc[op]
- if ok {
- return cmp(actualVals, expectArr)
- }
- return false
-}
-
-var floatSetCmpFunc = map[string]func([]float64, []float64) bool{
- opInter: floatSetInter,
- opNotInter: floatSetNotInter,
- opIn: floatSetBelong,
- opNotIn: floatSetNotBelong,
-}
-
-func cmpFloatSet(actualVals []float64, expectVals []string, op string) bool {
- expectArr := make([]float64, 0, len(expectVals))
- for _, expect := range expectVals {
- v, err := strconv.ParseFloat(removeQuote(expect), 64)
- if nil != err {
- return false
- }
- expectArr = append(expectArr, v)
- }
- cmp, ok := floatSetCmpFunc[op]
- if ok {
- return cmp(actualVals, expectArr)
- }
- return false
-}
-
-var stringSetCmpFunc = map[string]func([]string, []string) bool{
- opInter: strSetInter,
- opNotInter: strSetNotInter,
- opIn: strSetBelong,
- opNotIn: strSetNotBelong,
-}
-
-func cmpStringSet(actual []string, expect []string, op string) bool {
- cmp, ok := stringSetCmpFunc[op]
- if !ok {
- return false
- }
- expectVals := make([]string, 0, len(expect))
- for _, v := range expect {
- expectVals = append(expectVals, removeQuote(v))
- }
- return cmp(actual, expectVals)
-}
-
-func intSetBelong(actualVals []int64, expectVals []int64) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || len(actualVals) > length {
- return false
- }
- expectArr := i64Arr(expectVals)
- sort.Sort(expectArr)
- for _, actual := range actualVals {
- t := sort.Search(length, func(i int) bool {
- return actual <= expectArr[i]
- })
- if t >= length || actual != expectArr[t] {
- return false
- }
- }
- return true
-}
-
-func intSetNotBelong(actualVals []int64, expectVals []int64) bool {
- return !intSetBelong(actualVals, expectVals)
-}
-
-func intSetInter(actualVals []int64, expectVals []int64) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || length == 0 {
- return false
- }
- expectArr := i64Arr(expectVals)
- sort.Sort(expectArr)
- for _, actual := range actualVals {
- t := sort.Search(length, func(i int) bool {
- return actual <= expectArr[i]
- })
- if t < length && actual == expectArr[t] {
- return true
- }
- }
- return false
-}
-
-func intSetNotInter(actualVals []int64, expectVals []int64) bool {
- return !intSetInter(actualVals, expectVals)
-}
-
-type i64Arr []int64
-
-func (arr i64Arr) Len() int {
- return len(arr)
-}
-
-func (arr i64Arr) Less(i, j int) bool {
- return arr[i] < arr[j]
-}
-
-func (arr i64Arr) Swap(i, j int) {
- arr[i], arr[j] = arr[j], arr[i]
-}
-
-func floatSetBelong(actualVals []float64, expectVals []float64) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || len(actualVals) > length {
- return false
- }
- sort.Float64s(expectVals)
- for _, actual := range actualVals {
- t := sort.Search(length, func(i int) bool {
- return floatLessEqual(actual, expectVals[i])
- })
- if t >= length || !floatEqual(actual, expectVals[t]) {
- return false
- }
- }
- return true
-}
-
-func floatSetNotBelong(actualVals []float64, expectVals []float64) bool {
- return !floatSetBelong(actualVals, expectVals)
-}
-
-func floatSetInter(actualVals []float64, expectVals []float64) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || length == 0 {
- return false
- }
- sort.Float64s(expectVals)
- for _, actual := range actualVals {
- t := sort.Search(length, func(i int) bool {
- return floatLessEqual(actual, expectVals[i])
- })
- if t < length && floatEqual(actual, expectVals[t]) {
- return true
- }
- }
- return false
-}
-
-func floatSetNotInter(actualVals []float64, expectVals []float64) bool {
- return !floatSetInter(actualVals, expectVals)
-}
-
-func strSetBelong(actualVals []string, expectVals []string) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || len(actualVals) > length {
- return false
- }
- sort.Strings(expectVals)
- for _, actual := range actualVals {
- t := sort.SearchStrings(expectVals, actual)
- if t >= length || actual != expectVals[t] {
- return false
- }
- }
- return true
-}
-
-func strSetNotBelong(actualVals []string, expectVals []string) bool {
- return !strSetBelong(actualVals, expectVals)
-}
-
-func strSetInter(actualVals []string, expectVals []string) bool {
- length := len(expectVals)
- if len(actualVals) == 0 || length == 0 {
- return false
- }
- sort.Strings(expectVals)
- for _, actual := range actualVals {
- t := sort.SearchStrings(expectVals, actual)
- if t < length && actual == expectVals[t] {
- return true
- }
- }
- return false
-}
-
-func strSetNotInter(actualVals []string, expectVals []string) bool {
- return !strSetInter(actualVals, expectVals)
-}
-
-func floatEqual(a, b float64) bool {
- return math.Abs(a-b) < epsilon
-}
-
-func floatLessEqual(a, b float64) bool {
- return a < b || floatEqual(a, b)
-}
diff --git a/vendor/github.com/caibirdme/yql/doc.go b/vendor/github.com/caibirdme/yql/doc.go
deleted file mode 100644
index 695cd32..0000000
--- a/vendor/github.com/caibirdme/yql/doc.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Package yql implements sql-like grammar for rule engines.
-
-yql support compare operators like:
-
- =
- !=
- >
- >=
- <
- <=
- in
- !in
- ∩ // intersection (not the letter n)
- !∩
-
-below are legal yqls:
-
- a=1 and b>2 and (c<=3 or d in ('boy','girl')) or e ∩ (1,2,3)
- a=boy and b=1 or c in ('boy','girl')
- // boy will be interpreted as string if the type of a is string
- // 1 will be interpreted according to b's type
-
-for more details,see yql_test.go
-*/
-package yql
diff --git a/vendor/github.com/caibirdme/yql/helper.go b/vendor/github.com/caibirdme/yql/helper.go
deleted file mode 100644
index 7a4e266..0000000
--- a/vendor/github.com/caibirdme/yql/helper.go
+++ /dev/null
@@ -1,212 +0,0 @@
-package yql
-
-import (
- "fmt"
- "reflect"
-)
-
-var supportFuncHandler = map[string]func(interface{}) interface{}{
- "count": countRunner,
- "sum": sumRunner,
- "avg": avgRunner,
- "max": maxRunner,
- "min": minRunner,
-}
-
-func errFuncNotSupport(funcName string) error {
- return fmt.Errorf("%s isn't supported", funcName)
-}
-
-func funcRuner(actual interface{}, funcs []string) (interface{}, error) {
- if 0 == len(funcs) {
- return actual, nil
- }
- for _, fName := range funcs {
- fn, ok := supportFuncHandler[fName]
- if !ok {
- return nil, errFuncNotSupport(fName)
- }
- actual = fn(actual)
- }
- return actual, nil
-}
-
-func countRunner(in interface{}) interface{} {
- arr := reflect.ValueOf(in)
- if arr.Type().Kind() == reflect.Slice {
- return arr.Len()
- }
- return 1
-}
-
-func sumRunner(in interface{}) interface{} {
- switch t := in.(type) {
- case []int:
- return sumInt(t)
- case []int64:
- return sumInt64(t)
- case []float64:
- return sumFloat64(t)
- default:
- return in
- }
-}
-
-func sumInt(arr []int) int {
- var res int
- for _, v := range arr {
- res += v
- }
- return res
-}
-
-func sumInt64(arr []int64) int64 {
- var res int64
- for _, v := range arr {
- res += v
- }
- return res
-}
-
-func sumFloat64(arr []float64) float64 {
- var res float64
- for _, v := range arr {
- res += v
- }
- return res
-}
-
-func maxRunner(in interface{}) interface{} {
- switch t := in.(type) {
- case []int:
- return maxInt(t)
- case []int64:
- return maxInt64(t)
- case []float64:
- return maxFloat64(t)
- default:
- return in
- }
-}
-
-func maxInt(arr []int) int {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t > res {
- res = t
- }
- }
- return res
-}
-
-func maxInt64(arr []int64) int64 {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t > res {
- res = t
- }
- }
- return res
-}
-
-func maxFloat64(arr []float64) float64 {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t > res {
- res = t
- }
- }
- return res
-}
-
-func minRunner(in interface{}) interface{} {
- switch t := in.(type) {
- case []int:
- return minInt(t)
- case []int64:
- return minInt64(t)
- case []float64:
- return minFloat64(t)
- default:
- return in
- }
-}
-
-func minInt(arr []int) int {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t < res {
- res = t
- }
- }
- return res
-}
-
-func minInt64(arr []int64) int64 {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t < res {
- res = t
- }
- }
- return res
-}
-
-func minFloat64(arr []float64) float64 {
- var res = arr[0]
- length := len(arr)
- for i := 1; i < length; i++ {
- t := arr[i]
- if t < res {
- res = t
- }
- }
- return res
-}
-
-func avgRunner(in interface{}) interface{} {
- switch t := in.(type) {
- case []int:
- return avgInt(t)
- case []int64:
- return avgInt64(t)
- case []float64:
- return avgFloat64(t)
- default:
- return in
- }
-}
-
-func avgInt(arr []int) float64 {
- var total int
- for _, v := range arr {
- total += v
- }
- return float64(total) / float64(len(arr))
-}
-
-func avgInt64(arr []int64) float64 {
- var total int64
- for _, v := range arr {
- total += v
- }
- return float64(total) / float64(len(arr))
-}
-
-func avgFloat64(arr []float64) float64 {
- var total float64
- for _, v := range arr {
- total += v
- }
- return total / float64(len(arr))
-}
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/Yql.g4 b/vendor/github.com/caibirdme/yql/internal/grammar/Yql.g4
deleted file mode 100644
index 5fdf47b..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/Yql.g4
+++ /dev/null
@@ -1,26 +0,0 @@
-grammar Yql;
-
-query: expr;
-
-expr: booleanExpr #boolExpr
- | expr 'and' expr #andExpr
- | expr 'or' expr #orExpr
- | '(' expr ')' #embbedExpr
- ;
-
-booleanExpr: leftexpr op=('='|'!='|'>'|'<'|'>='|'<=') value
- | leftexpr op=('in'|'!in'|'∩'|'!∩') '(' value (',' value)* ')'
- ;
-leftexpr: FIELDNAME (('.' FUNC '()')+)?
- ;
-value: STRING | INT | FLOAT | TRUE | FALSE;
-
-TRUE: 'true';
-FALSE: 'false';
-FUNC: 'count'|'sum'|'avg'|'max'|'min';
-FIELDNAME: ([a-zA-Z]|'_')+;
-STRING: '\'' .*? '\'';
-fragment DIGIT: [0-9];
-INT: ('+'|'-')? DIGIT+;
-FLOAT: ('+'|'-')? DIGIT+ '.' DIGIT*;
-WS: [ \t\r\n]+ -> skip;
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/Yql.tokens b/vendor/github.com/caibirdme/yql/internal/grammar/Yql.tokens
deleted file mode 100644
index f1eaaae..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/Yql.tokens
+++ /dev/null
@@ -1,44 +0,0 @@
-T__0=1
-T__1=2
-T__2=3
-T__3=4
-T__4=5
-T__5=6
-T__6=7
-T__7=8
-T__8=9
-T__9=10
-T__10=11
-T__11=12
-T__12=13
-T__13=14
-T__14=15
-T__15=16
-T__16=17
-TRUE=18
-FALSE=19
-FUNC=20
-FIELDNAME=21
-STRING=22
-INT=23
-FLOAT=24
-WS=25
-'and'=1
-'or'=2
-'('=3
-')'=4
-'='=5
-'!='=6
-'>'=7
-'<'=8
-'>='=9
-'<='=10
-'in'=11
-'!in'=12
-'∩'=13
-'!∩'=14
-','=15
-'.'=16
-'()'=17
-'true'=18
-'false'=19
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/YqlLexer.tokens b/vendor/github.com/caibirdme/yql/internal/grammar/YqlLexer.tokens
deleted file mode 100644
index f1eaaae..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/YqlLexer.tokens
+++ /dev/null
@@ -1,44 +0,0 @@
-T__0=1
-T__1=2
-T__2=3
-T__3=4
-T__4=5
-T__5=6
-T__6=7
-T__7=8
-T__8=9
-T__9=10
-T__10=11
-T__11=12
-T__12=13
-T__13=14
-T__14=15
-T__15=16
-T__16=17
-TRUE=18
-FALSE=19
-FUNC=20
-FIELDNAME=21
-STRING=22
-INT=23
-FLOAT=24
-WS=25
-'and'=1
-'or'=2
-'('=3
-')'=4
-'='=5
-'!='=6
-'>'=7
-'<'=8
-'>='=9
-'<='=10
-'in'=11
-'!in'=12
-'∩'=13
-'!∩'=14
-','=15
-'.'=16
-'()'=17
-'true'=18
-'false'=19
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/yql_base_listener.go b/vendor/github.com/caibirdme/yql/internal/grammar/yql_base_listener.go
deleted file mode 100644
index a9b7c6c..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/yql_base_listener.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Generated from Yql.g4 by ANTLR 4.7.
-
-package grammar // Yql
-import "github.com/antlr/antlr4/runtime/Go/antlr"
-
-// BaseYqlListener is a complete listener for a parse tree produced by YqlParser.
-type BaseYqlListener struct{}
-
-var _ YqlListener = &BaseYqlListener{}
-
-// VisitTerminal is called when a terminal node is visited.
-func (s *BaseYqlListener) VisitTerminal(node antlr.TerminalNode) {}
-
-// VisitErrorNode is called when an error node is visited.
-func (s *BaseYqlListener) VisitErrorNode(node antlr.ErrorNode) {}
-
-// EnterEveryRule is called when any rule is entered.
-func (s *BaseYqlListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}
-
-// ExitEveryRule is called when any rule is exited.
-func (s *BaseYqlListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}
-
-// EnterQuery is called when production query is entered.
-func (s *BaseYqlListener) EnterQuery(ctx *QueryContext) {}
-
-// ExitQuery is called when production query is exited.
-func (s *BaseYqlListener) ExitQuery(ctx *QueryContext) {}
-
-// EnterEmbbedExpr is called when production embbedExpr is entered.
-func (s *BaseYqlListener) EnterEmbbedExpr(ctx *EmbbedExprContext) {}
-
-// ExitEmbbedExpr is called when production embbedExpr is exited.
-func (s *BaseYqlListener) ExitEmbbedExpr(ctx *EmbbedExprContext) {}
-
-// EnterOrExpr is called when production orExpr is entered.
-func (s *BaseYqlListener) EnterOrExpr(ctx *OrExprContext) {}
-
-// ExitOrExpr is called when production orExpr is exited.
-func (s *BaseYqlListener) ExitOrExpr(ctx *OrExprContext) {}
-
-// EnterBoolExpr is called when production boolExpr is entered.
-func (s *BaseYqlListener) EnterBoolExpr(ctx *BoolExprContext) {}
-
-// ExitBoolExpr is called when production boolExpr is exited.
-func (s *BaseYqlListener) ExitBoolExpr(ctx *BoolExprContext) {}
-
-// EnterAndExpr is called when production andExpr is entered.
-func (s *BaseYqlListener) EnterAndExpr(ctx *AndExprContext) {}
-
-// ExitAndExpr is called when production andExpr is exited.
-func (s *BaseYqlListener) ExitAndExpr(ctx *AndExprContext) {}
-
-// EnterBooleanExpr is called when production booleanExpr is entered.
-func (s *BaseYqlListener) EnterBooleanExpr(ctx *BooleanExprContext) {}
-
-// ExitBooleanExpr is called when production booleanExpr is exited.
-func (s *BaseYqlListener) ExitBooleanExpr(ctx *BooleanExprContext) {}
-
-// EnterLeftexpr is called when production leftexpr is entered.
-func (s *BaseYqlListener) EnterLeftexpr(ctx *LeftexprContext) {}
-
-// ExitLeftexpr is called when production leftexpr is exited.
-func (s *BaseYqlListener) ExitLeftexpr(ctx *LeftexprContext) {}
-
-// EnterValue is called when production value is entered.
-func (s *BaseYqlListener) EnterValue(ctx *ValueContext) {}
-
-// ExitValue is called when production value is exited.
-func (s *BaseYqlListener) ExitValue(ctx *ValueContext) {}
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/yql_lexer.go b/vendor/github.com/caibirdme/yql/internal/grammar/yql_lexer.go
deleted file mode 100644
index 25f2c96..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/yql_lexer.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// Generated from Yql.g4 by ANTLR 4.7.
-
-package grammar
-
-import (
- "fmt"
- "unicode"
-
- "github.com/antlr/antlr4/runtime/Go/antlr"
-)
-
-// Suppress unused import error
-var _ = fmt.Printf
-var _ = unicode.IsLetter
-
-var serializedLexerAtn = []uint16{
- 3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 2, 27, 176,
- 8, 1, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7,
- 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12,
- 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4,
- 18, 9, 18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 4, 23,
- 9, 23, 4, 24, 9, 24, 4, 25, 9, 25, 4, 26, 9, 26, 4, 27, 9, 27, 3, 2, 3,
- 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 5, 3, 5, 3, 6, 3, 6, 3,
- 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10, 3, 10, 3, 11, 3, 11,
- 3, 11, 3, 12, 3, 12, 3, 12, 3, 13, 3, 13, 3, 13, 3, 13, 3, 14, 3, 14, 3,
- 15, 3, 15, 3, 15, 3, 16, 3, 16, 3, 17, 3, 17, 3, 18, 3, 18, 3, 18, 3, 19,
- 3, 19, 3, 19, 3, 19, 3, 19, 3, 20, 3, 20, 3, 20, 3, 20, 3, 20, 3, 20, 3,
- 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21,
- 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 3, 21, 5, 21, 129, 10, 21, 3, 22, 6,
- 22, 132, 10, 22, 13, 22, 14, 22, 133, 3, 23, 3, 23, 7, 23, 138, 10, 23,
- 12, 23, 14, 23, 141, 11, 23, 3, 23, 3, 23, 3, 24, 3, 24, 3, 25, 5, 25,
- 148, 10, 25, 3, 25, 6, 25, 151, 10, 25, 13, 25, 14, 25, 152, 3, 26, 5,
- 26, 156, 10, 26, 3, 26, 6, 26, 159, 10, 26, 13, 26, 14, 26, 160, 3, 26,
- 3, 26, 7, 26, 165, 10, 26, 12, 26, 14, 26, 168, 11, 26, 3, 27, 6, 27, 171,
- 10, 27, 13, 27, 14, 27, 172, 3, 27, 3, 27, 3, 139, 2, 28, 3, 3, 5, 4, 7,
- 5, 9, 6, 11, 7, 13, 8, 15, 9, 17, 10, 19, 11, 21, 12, 23, 13, 25, 14, 27,
- 15, 29, 16, 31, 17, 33, 18, 35, 19, 37, 20, 39, 21, 41, 22, 43, 23, 45,
- 24, 47, 2, 49, 25, 51, 26, 53, 27, 3, 2, 6, 5, 2, 67, 92, 97, 97, 99, 124,
- 3, 2, 50, 59, 4, 2, 45, 45, 47, 47, 5, 2, 11, 12, 15, 15, 34, 34, 2, 186,
- 2, 3, 3, 2, 2, 2, 2, 5, 3, 2, 2, 2, 2, 7, 3, 2, 2, 2, 2, 9, 3, 2, 2, 2,
- 2, 11, 3, 2, 2, 2, 2, 13, 3, 2, 2, 2, 2, 15, 3, 2, 2, 2, 2, 17, 3, 2, 2,
- 2, 2, 19, 3, 2, 2, 2, 2, 21, 3, 2, 2, 2, 2, 23, 3, 2, 2, 2, 2, 25, 3, 2,
- 2, 2, 2, 27, 3, 2, 2, 2, 2, 29, 3, 2, 2, 2, 2, 31, 3, 2, 2, 2, 2, 33, 3,
- 2, 2, 2, 2, 35, 3, 2, 2, 2, 2, 37, 3, 2, 2, 2, 2, 39, 3, 2, 2, 2, 2, 41,
- 3, 2, 2, 2, 2, 43, 3, 2, 2, 2, 2, 45, 3, 2, 2, 2, 2, 49, 3, 2, 2, 2, 2,
- 51, 3, 2, 2, 2, 2, 53, 3, 2, 2, 2, 3, 55, 3, 2, 2, 2, 5, 59, 3, 2, 2, 2,
- 7, 62, 3, 2, 2, 2, 9, 64, 3, 2, 2, 2, 11, 66, 3, 2, 2, 2, 13, 68, 3, 2,
- 2, 2, 15, 71, 3, 2, 2, 2, 17, 73, 3, 2, 2, 2, 19, 75, 3, 2, 2, 2, 21, 78,
- 3, 2, 2, 2, 23, 81, 3, 2, 2, 2, 25, 84, 3, 2, 2, 2, 27, 88, 3, 2, 2, 2,
- 29, 90, 3, 2, 2, 2, 31, 93, 3, 2, 2, 2, 33, 95, 3, 2, 2, 2, 35, 97, 3,
- 2, 2, 2, 37, 100, 3, 2, 2, 2, 39, 105, 3, 2, 2, 2, 41, 128, 3, 2, 2, 2,
- 43, 131, 3, 2, 2, 2, 45, 135, 3, 2, 2, 2, 47, 144, 3, 2, 2, 2, 49, 147,
- 3, 2, 2, 2, 51, 155, 3, 2, 2, 2, 53, 170, 3, 2, 2, 2, 55, 56, 7, 99, 2,
- 2, 56, 57, 7, 112, 2, 2, 57, 58, 7, 102, 2, 2, 58, 4, 3, 2, 2, 2, 59, 60,
- 7, 113, 2, 2, 60, 61, 7, 116, 2, 2, 61, 6, 3, 2, 2, 2, 62, 63, 7, 42, 2,
- 2, 63, 8, 3, 2, 2, 2, 64, 65, 7, 43, 2, 2, 65, 10, 3, 2, 2, 2, 66, 67,
- 7, 63, 2, 2, 67, 12, 3, 2, 2, 2, 68, 69, 7, 35, 2, 2, 69, 70, 7, 63, 2,
- 2, 70, 14, 3, 2, 2, 2, 71, 72, 7, 64, 2, 2, 72, 16, 3, 2, 2, 2, 73, 74,
- 7, 62, 2, 2, 74, 18, 3, 2, 2, 2, 75, 76, 7, 64, 2, 2, 76, 77, 7, 63, 2,
- 2, 77, 20, 3, 2, 2, 2, 78, 79, 7, 62, 2, 2, 79, 80, 7, 63, 2, 2, 80, 22,
- 3, 2, 2, 2, 81, 82, 7, 107, 2, 2, 82, 83, 7, 112, 2, 2, 83, 24, 3, 2, 2,
- 2, 84, 85, 7, 35, 2, 2, 85, 86, 7, 107, 2, 2, 86, 87, 7, 112, 2, 2, 87,
- 26, 3, 2, 2, 2, 88, 89, 7, 8747, 2, 2, 89, 28, 3, 2, 2, 2, 90, 91, 7, 35,
- 2, 2, 91, 92, 7, 8747, 2, 2, 92, 30, 3, 2, 2, 2, 93, 94, 7, 46, 2, 2, 94,
- 32, 3, 2, 2, 2, 95, 96, 7, 48, 2, 2, 96, 34, 3, 2, 2, 2, 97, 98, 7, 42,
- 2, 2, 98, 99, 7, 43, 2, 2, 99, 36, 3, 2, 2, 2, 100, 101, 7, 118, 2, 2,
- 101, 102, 7, 116, 2, 2, 102, 103, 7, 119, 2, 2, 103, 104, 7, 103, 2, 2,
- 104, 38, 3, 2, 2, 2, 105, 106, 7, 104, 2, 2, 106, 107, 7, 99, 2, 2, 107,
- 108, 7, 110, 2, 2, 108, 109, 7, 117, 2, 2, 109, 110, 7, 103, 2, 2, 110,
- 40, 3, 2, 2, 2, 111, 112, 7, 101, 2, 2, 112, 113, 7, 113, 2, 2, 113, 114,
- 7, 119, 2, 2, 114, 115, 7, 112, 2, 2, 115, 129, 7, 118, 2, 2, 116, 117,
- 7, 117, 2, 2, 117, 118, 7, 119, 2, 2, 118, 129, 7, 111, 2, 2, 119, 120,
- 7, 99, 2, 2, 120, 121, 7, 120, 2, 2, 121, 129, 7, 105, 2, 2, 122, 123,
- 7, 111, 2, 2, 123, 124, 7, 99, 2, 2, 124, 129, 7, 122, 2, 2, 125, 126,
- 7, 111, 2, 2, 126, 127, 7, 107, 2, 2, 127, 129, 7, 112, 2, 2, 128, 111,
- 3, 2, 2, 2, 128, 116, 3, 2, 2, 2, 128, 119, 3, 2, 2, 2, 128, 122, 3, 2,
- 2, 2, 128, 125, 3, 2, 2, 2, 129, 42, 3, 2, 2, 2, 130, 132, 9, 2, 2, 2,
- 131, 130, 3, 2, 2, 2, 132, 133, 3, 2, 2, 2, 133, 131, 3, 2, 2, 2, 133,
- 134, 3, 2, 2, 2, 134, 44, 3, 2, 2, 2, 135, 139, 7, 41, 2, 2, 136, 138,
- 11, 2, 2, 2, 137, 136, 3, 2, 2, 2, 138, 141, 3, 2, 2, 2, 139, 140, 3, 2,
- 2, 2, 139, 137, 3, 2, 2, 2, 140, 142, 3, 2, 2, 2, 141, 139, 3, 2, 2, 2,
- 142, 143, 7, 41, 2, 2, 143, 46, 3, 2, 2, 2, 144, 145, 9, 3, 2, 2, 145,
- 48, 3, 2, 2, 2, 146, 148, 9, 4, 2, 2, 147, 146, 3, 2, 2, 2, 147, 148, 3,
- 2, 2, 2, 148, 150, 3, 2, 2, 2, 149, 151, 5, 47, 24, 2, 150, 149, 3, 2,
- 2, 2, 151, 152, 3, 2, 2, 2, 152, 150, 3, 2, 2, 2, 152, 153, 3, 2, 2, 2,
- 153, 50, 3, 2, 2, 2, 154, 156, 9, 4, 2, 2, 155, 154, 3, 2, 2, 2, 155, 156,
- 3, 2, 2, 2, 156, 158, 3, 2, 2, 2, 157, 159, 5, 47, 24, 2, 158, 157, 3,
- 2, 2, 2, 159, 160, 3, 2, 2, 2, 160, 158, 3, 2, 2, 2, 160, 161, 3, 2, 2,
- 2, 161, 162, 3, 2, 2, 2, 162, 166, 7, 48, 2, 2, 163, 165, 5, 47, 24, 2,
- 164, 163, 3, 2, 2, 2, 165, 168, 3, 2, 2, 2, 166, 164, 3, 2, 2, 2, 166,
- 167, 3, 2, 2, 2, 167, 52, 3, 2, 2, 2, 168, 166, 3, 2, 2, 2, 169, 171, 9,
- 5, 2, 2, 170, 169, 3, 2, 2, 2, 171, 172, 3, 2, 2, 2, 172, 170, 3, 2, 2,
- 2, 172, 173, 3, 2, 2, 2, 173, 174, 3, 2, 2, 2, 174, 175, 8, 27, 2, 2, 175,
- 54, 3, 2, 2, 2, 13, 2, 128, 131, 133, 139, 147, 152, 155, 160, 166, 172,
- 3, 8, 2, 2,
-}
-
-var lexerDeserializer = antlr.NewATNDeserializer(nil)
-var lexerAtn = lexerDeserializer.DeserializeFromUInt16(serializedLexerAtn)
-
-var lexerChannelNames = []string{
- "DEFAULT_TOKEN_CHANNEL", "HIDDEN",
-}
-
-var lexerModeNames = []string{
- "DEFAULT_MODE",
-}
-
-var lexerLiteralNames = []string{
- "", "'and'", "'or'", "'('", "')'", "'='", "'!='", "'>'", "'<'", "'>='",
- "'<='", "'in'", "'!in'", "'\u2229'", "'!\u2229'", "','", "'.'", "'()'",
- "'true'", "'false'",
-}
-
-var lexerSymbolicNames = []string{
- "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
- "TRUE", "FALSE", "FUNC", "FIELDNAME", "STRING", "INT", "FLOAT", "WS",
-}
-
-var lexerRuleNames = []string{
- "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8",
- "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16",
- "TRUE", "FALSE", "FUNC", "FIELDNAME", "STRING", "DIGIT", "INT", "FLOAT",
- "WS",
-}
-
-type YqlLexer struct {
- *antlr.BaseLexer
- channelNames []string
- modeNames []string
- // TODO: EOF string
-}
-
-var lexerDecisionToDFA = make([]*antlr.DFA, len(lexerAtn.DecisionToState))
-
-func init() {
- for index, ds := range lexerAtn.DecisionToState {
- lexerDecisionToDFA[index] = antlr.NewDFA(ds, index)
- }
-}
-
-func NewYqlLexer(input antlr.CharStream) *YqlLexer {
-
- l := new(YqlLexer)
-
- l.BaseLexer = antlr.NewBaseLexer(input)
- l.Interpreter = antlr.NewLexerATNSimulator(l, lexerAtn, lexerDecisionToDFA, antlr.NewPredictionContextCache())
-
- l.channelNames = lexerChannelNames
- l.modeNames = lexerModeNames
- l.RuleNames = lexerRuleNames
- l.LiteralNames = lexerLiteralNames
- l.SymbolicNames = lexerSymbolicNames
- l.GrammarFileName = "Yql.g4"
- // TODO: l.EOF = antlr.TokenEOF
-
- return l
-}
-
-// YqlLexer tokens.
-const (
- YqlLexerT__0 = 1
- YqlLexerT__1 = 2
- YqlLexerT__2 = 3
- YqlLexerT__3 = 4
- YqlLexerT__4 = 5
- YqlLexerT__5 = 6
- YqlLexerT__6 = 7
- YqlLexerT__7 = 8
- YqlLexerT__8 = 9
- YqlLexerT__9 = 10
- YqlLexerT__10 = 11
- YqlLexerT__11 = 12
- YqlLexerT__12 = 13
- YqlLexerT__13 = 14
- YqlLexerT__14 = 15
- YqlLexerT__15 = 16
- YqlLexerT__16 = 17
- YqlLexerTRUE = 18
- YqlLexerFALSE = 19
- YqlLexerFUNC = 20
- YqlLexerFIELDNAME = 21
- YqlLexerSTRING = 22
- YqlLexerINT = 23
- YqlLexerFLOAT = 24
- YqlLexerWS = 25
-)
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/yql_listener.go b/vendor/github.com/caibirdme/yql/internal/grammar/yql_listener.go
deleted file mode 100644
index 7cdefaf..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/yql_listener.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Generated from Yql.g4 by ANTLR 4.7.
-
-package grammar // Yql
-import "github.com/antlr/antlr4/runtime/Go/antlr"
-
-// YqlListener is a complete listener for a parse tree produced by YqlParser.
-type YqlListener interface {
- antlr.ParseTreeListener
-
- // EnterQuery is called when entering the query production.
- EnterQuery(c *QueryContext)
-
- // EnterEmbbedExpr is called when entering the embbedExpr production.
- EnterEmbbedExpr(c *EmbbedExprContext)
-
- // EnterOrExpr is called when entering the orExpr production.
- EnterOrExpr(c *OrExprContext)
-
- // EnterBoolExpr is called when entering the boolExpr production.
- EnterBoolExpr(c *BoolExprContext)
-
- // EnterAndExpr is called when entering the andExpr production.
- EnterAndExpr(c *AndExprContext)
-
- // EnterBooleanExpr is called when entering the booleanExpr production.
- EnterBooleanExpr(c *BooleanExprContext)
-
- // EnterLeftexpr is called when entering the leftexpr production.
- EnterLeftexpr(c *LeftexprContext)
-
- // EnterValue is called when entering the value production.
- EnterValue(c *ValueContext)
-
- // ExitQuery is called when exiting the query production.
- ExitQuery(c *QueryContext)
-
- // ExitEmbbedExpr is called when exiting the embbedExpr production.
- ExitEmbbedExpr(c *EmbbedExprContext)
-
- // ExitOrExpr is called when exiting the orExpr production.
- ExitOrExpr(c *OrExprContext)
-
- // ExitBoolExpr is called when exiting the boolExpr production.
- ExitBoolExpr(c *BoolExprContext)
-
- // ExitAndExpr is called when exiting the andExpr production.
- ExitAndExpr(c *AndExprContext)
-
- // ExitBooleanExpr is called when exiting the booleanExpr production.
- ExitBooleanExpr(c *BooleanExprContext)
-
- // ExitLeftexpr is called when exiting the leftexpr production.
- ExitLeftexpr(c *LeftexprContext)
-
- // ExitValue is called when exiting the value production.
- ExitValue(c *ValueContext)
-}
diff --git a/vendor/github.com/caibirdme/yql/internal/grammar/yql_parser.go b/vendor/github.com/caibirdme/yql/internal/grammar/yql_parser.go
deleted file mode 100644
index 7ca566a..0000000
--- a/vendor/github.com/caibirdme/yql/internal/grammar/yql_parser.go
+++ /dev/null
@@ -1,1063 +0,0 @@
-// Generated from Yql.g4 by ANTLR 4.7.
-
-package grammar // Yql
-import (
- "fmt"
- "reflect"
- "strconv"
-
- "github.com/antlr/antlr4/runtime/Go/antlr"
-)
-
-// Suppress unused import errors
-var _ = fmt.Printf
-var _ = reflect.Copy
-var _ = strconv.Itoa
-
-var parserATN = []uint16{
- 3, 24715, 42794, 33075, 47597, 16764, 15335, 30598, 22884, 3, 27, 65, 4,
- 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 3, 2, 3, 2, 3,
- 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 21, 10, 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 7, 3, 29, 10, 3, 12, 3, 14, 3, 32, 11, 3, 3, 4, 3, 4, 3,
- 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 7, 4, 44, 10, 4, 12, 4, 14,
- 4, 47, 11, 4, 3, 4, 3, 4, 5, 4, 51, 10, 4, 3, 5, 3, 5, 3, 5, 3, 5, 6, 5,
- 57, 10, 5, 13, 5, 14, 5, 58, 5, 5, 61, 10, 5, 3, 6, 3, 6, 3, 6, 2, 3, 4,
- 7, 2, 4, 6, 8, 10, 2, 5, 3, 2, 7, 12, 3, 2, 13, 16, 4, 2, 20, 21, 24, 26,
- 2, 66, 2, 12, 3, 2, 2, 2, 4, 20, 3, 2, 2, 2, 6, 50, 3, 2, 2, 2, 8, 52,
- 3, 2, 2, 2, 10, 62, 3, 2, 2, 2, 12, 13, 5, 4, 3, 2, 13, 3, 3, 2, 2, 2,
- 14, 15, 8, 3, 1, 2, 15, 21, 5, 6, 4, 2, 16, 17, 7, 5, 2, 2, 17, 18, 5,
- 4, 3, 2, 18, 19, 7, 6, 2, 2, 19, 21, 3, 2, 2, 2, 20, 14, 3, 2, 2, 2, 20,
- 16, 3, 2, 2, 2, 21, 30, 3, 2, 2, 2, 22, 23, 12, 5, 2, 2, 23, 24, 7, 3,
- 2, 2, 24, 29, 5, 4, 3, 6, 25, 26, 12, 4, 2, 2, 26, 27, 7, 4, 2, 2, 27,
- 29, 5, 4, 3, 5, 28, 22, 3, 2, 2, 2, 28, 25, 3, 2, 2, 2, 29, 32, 3, 2, 2,
- 2, 30, 28, 3, 2, 2, 2, 30, 31, 3, 2, 2, 2, 31, 5, 3, 2, 2, 2, 32, 30, 3,
- 2, 2, 2, 33, 34, 5, 8, 5, 2, 34, 35, 9, 2, 2, 2, 35, 36, 5, 10, 6, 2, 36,
- 51, 3, 2, 2, 2, 37, 38, 5, 8, 5, 2, 38, 39, 9, 3, 2, 2, 39, 40, 7, 5, 2,
- 2, 40, 45, 5, 10, 6, 2, 41, 42, 7, 17, 2, 2, 42, 44, 5, 10, 6, 2, 43, 41,
- 3, 2, 2, 2, 44, 47, 3, 2, 2, 2, 45, 43, 3, 2, 2, 2, 45, 46, 3, 2, 2, 2,
- 46, 48, 3, 2, 2, 2, 47, 45, 3, 2, 2, 2, 48, 49, 7, 6, 2, 2, 49, 51, 3,
- 2, 2, 2, 50, 33, 3, 2, 2, 2, 50, 37, 3, 2, 2, 2, 51, 7, 3, 2, 2, 2, 52,
- 60, 7, 23, 2, 2, 53, 54, 7, 18, 2, 2, 54, 55, 7, 22, 2, 2, 55, 57, 7, 19,
- 2, 2, 56, 53, 3, 2, 2, 2, 57, 58, 3, 2, 2, 2, 58, 56, 3, 2, 2, 2, 58, 59,
- 3, 2, 2, 2, 59, 61, 3, 2, 2, 2, 60, 56, 3, 2, 2, 2, 60, 61, 3, 2, 2, 2,
- 61, 9, 3, 2, 2, 2, 62, 63, 9, 4, 2, 2, 63, 11, 3, 2, 2, 2, 9, 20, 28, 30,
- 45, 50, 58, 60,
-}
-var deserializer = antlr.NewATNDeserializer(nil)
-var deserializedATN = deserializer.DeserializeFromUInt16(parserATN)
-
-var literalNames = []string{
- "", "'and'", "'or'", "'('", "')'", "'='", "'!='", "'>'", "'<'", "'>='",
- "'<='", "'in'", "'!in'", "'\u2229'", "'!\u2229'", "','", "'.'", "'()'",
- "'true'", "'false'",
-}
-var symbolicNames = []string{
- "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
- "TRUE", "FALSE", "FUNC", "FIELDNAME", "STRING", "INT", "FLOAT", "WS",
-}
-
-var ruleNames = []string{
- "query", "expr", "booleanExpr", "leftexpr", "value",
-}
-var decisionToDFA = make([]*antlr.DFA, len(deserializedATN.DecisionToState))
-
-func init() {
- for index, ds := range deserializedATN.DecisionToState {
- decisionToDFA[index] = antlr.NewDFA(ds, index)
- }
-}
-
-type YqlParser struct {
- *antlr.BaseParser
-}
-
-func NewYqlParser(input antlr.TokenStream) *YqlParser {
- this := new(YqlParser)
-
- this.BaseParser = antlr.NewBaseParser(input)
-
- this.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())
- this.RuleNames = ruleNames
- this.LiteralNames = literalNames
- this.SymbolicNames = symbolicNames
- this.GrammarFileName = "Yql.g4"
-
- return this
-}
-
-// YqlParser tokens.
-const (
- YqlParserEOF = antlr.TokenEOF
- YqlParserT__0 = 1
- YqlParserT__1 = 2
- YqlParserT__2 = 3
- YqlParserT__3 = 4
- YqlParserT__4 = 5
- YqlParserT__5 = 6
- YqlParserT__6 = 7
- YqlParserT__7 = 8
- YqlParserT__8 = 9
- YqlParserT__9 = 10
- YqlParserT__10 = 11
- YqlParserT__11 = 12
- YqlParserT__12 = 13
- YqlParserT__13 = 14
- YqlParserT__14 = 15
- YqlParserT__15 = 16
- YqlParserT__16 = 17
- YqlParserTRUE = 18
- YqlParserFALSE = 19
- YqlParserFUNC = 20
- YqlParserFIELDNAME = 21
- YqlParserSTRING = 22
- YqlParserINT = 23
- YqlParserFLOAT = 24
- YqlParserWS = 25
-)
-
-// YqlParser rules.
-const (
- YqlParserRULE_query = 0
- YqlParserRULE_expr = 1
- YqlParserRULE_booleanExpr = 2
- YqlParserRULE_leftexpr = 3
- YqlParserRULE_value = 4
-)
-
-// IQueryContext is an interface to support dynamic dispatch.
-type IQueryContext interface {
- antlr.ParserRuleContext
-
- // GetParser returns the parser.
- GetParser() antlr.Parser
-
- // IsQueryContext differentiates from other interfaces.
- IsQueryContext()
-}
-
-type QueryContext struct {
- *antlr.BaseParserRuleContext
- parser antlr.Parser
-}
-
-func NewEmptyQueryContext() *QueryContext {
- var p = new(QueryContext)
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
- p.RuleIndex = YqlParserRULE_query
- return p
-}
-
-func (*QueryContext) IsQueryContext() {}
-
-func NewQueryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *QueryContext {
- var p = new(QueryContext)
-
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
-
- p.parser = parser
- p.RuleIndex = YqlParserRULE_query
-
- return p
-}
-
-func (s *QueryContext) GetParser() antlr.Parser { return s.parser }
-
-func (s *QueryContext) Expr() IExprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IExprContext)(nil)).Elem(), 0)
-
- if t == nil {
- return nil
- }
-
- return t.(IExprContext)
-}
-
-func (s *QueryContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *QueryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
- return antlr.TreesStringTree(s, ruleNames, recog)
-}
-
-func (s *QueryContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterQuery(s)
- }
-}
-
-func (s *QueryContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitQuery(s)
- }
-}
-
-func (p *YqlParser) Query() (localctx IQueryContext) {
- localctx = NewQueryContext(p, p.GetParserRuleContext(), p.GetState())
- p.EnterRule(localctx, 0, YqlParserRULE_query)
-
- defer func() {
- p.ExitRule()
- }()
-
- defer func() {
- if err := recover(); err != nil {
- if v, ok := err.(antlr.RecognitionException); ok {
- localctx.SetException(v)
- p.GetErrorHandler().ReportError(p, v)
- p.GetErrorHandler().Recover(p, v)
- } else {
- panic(err)
- }
- }
- }()
-
- p.EnterOuterAlt(localctx, 1)
- {
- p.SetState(10)
- p.expr(0)
- }
-
- return localctx
-}
-
-// IExprContext is an interface to support dynamic dispatch.
-type IExprContext interface {
- antlr.ParserRuleContext
-
- // GetParser returns the parser.
- GetParser() antlr.Parser
-
- // IsExprContext differentiates from other interfaces.
- IsExprContext()
-}
-
-type ExprContext struct {
- *antlr.BaseParserRuleContext
- parser antlr.Parser
-}
-
-func NewEmptyExprContext() *ExprContext {
- var p = new(ExprContext)
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
- p.RuleIndex = YqlParserRULE_expr
- return p
-}
-
-func (*ExprContext) IsExprContext() {}
-
-func NewExprContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ExprContext {
- var p = new(ExprContext)
-
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
-
- p.parser = parser
- p.RuleIndex = YqlParserRULE_expr
-
- return p
-}
-
-func (s *ExprContext) GetParser() antlr.Parser { return s.parser }
-
-func (s *ExprContext) CopyFrom(ctx *ExprContext) {
- s.BaseParserRuleContext.CopyFrom(ctx.BaseParserRuleContext)
-}
-
-func (s *ExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *ExprContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
- return antlr.TreesStringTree(s, ruleNames, recog)
-}
-
-type EmbbedExprContext struct {
- *ExprContext
-}
-
-func NewEmbbedExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *EmbbedExprContext {
- var p = new(EmbbedExprContext)
-
- p.ExprContext = NewEmptyExprContext()
- p.parser = parser
- p.CopyFrom(ctx.(*ExprContext))
-
- return p
-}
-
-func (s *EmbbedExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *EmbbedExprContext) Expr() IExprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IExprContext)(nil)).Elem(), 0)
-
- if t == nil {
- return nil
- }
-
- return t.(IExprContext)
-}
-
-func (s *EmbbedExprContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterEmbbedExpr(s)
- }
-}
-
-func (s *EmbbedExprContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitEmbbedExpr(s)
- }
-}
-
-type OrExprContext struct {
- *ExprContext
-}
-
-func NewOrExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *OrExprContext {
- var p = new(OrExprContext)
-
- p.ExprContext = NewEmptyExprContext()
- p.parser = parser
- p.CopyFrom(ctx.(*ExprContext))
-
- return p
-}
-
-func (s *OrExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *OrExprContext) AllExpr() []IExprContext {
- var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExprContext)(nil)).Elem())
- var tst = make([]IExprContext, len(ts))
-
- for i, t := range ts {
- if t != nil {
- tst[i] = t.(IExprContext)
- }
- }
-
- return tst
-}
-
-func (s *OrExprContext) Expr(i int) IExprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IExprContext)(nil)).Elem(), i)
-
- if t == nil {
- return nil
- }
-
- return t.(IExprContext)
-}
-
-func (s *OrExprContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterOrExpr(s)
- }
-}
-
-func (s *OrExprContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitOrExpr(s)
- }
-}
-
-type BoolExprContext struct {
- *ExprContext
-}
-
-func NewBoolExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *BoolExprContext {
- var p = new(BoolExprContext)
-
- p.ExprContext = NewEmptyExprContext()
- p.parser = parser
- p.CopyFrom(ctx.(*ExprContext))
-
- return p
-}
-
-func (s *BoolExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *BoolExprContext) BooleanExpr() IBooleanExprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IBooleanExprContext)(nil)).Elem(), 0)
-
- if t == nil {
- return nil
- }
-
- return t.(IBooleanExprContext)
-}
-
-func (s *BoolExprContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterBoolExpr(s)
- }
-}
-
-func (s *BoolExprContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitBoolExpr(s)
- }
-}
-
-type AndExprContext struct {
- *ExprContext
-}
-
-func NewAndExprContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *AndExprContext {
- var p = new(AndExprContext)
-
- p.ExprContext = NewEmptyExprContext()
- p.parser = parser
- p.CopyFrom(ctx.(*ExprContext))
-
- return p
-}
-
-func (s *AndExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *AndExprContext) AllExpr() []IExprContext {
- var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IExprContext)(nil)).Elem())
- var tst = make([]IExprContext, len(ts))
-
- for i, t := range ts {
- if t != nil {
- tst[i] = t.(IExprContext)
- }
- }
-
- return tst
-}
-
-func (s *AndExprContext) Expr(i int) IExprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IExprContext)(nil)).Elem(), i)
-
- if t == nil {
- return nil
- }
-
- return t.(IExprContext)
-}
-
-func (s *AndExprContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterAndExpr(s)
- }
-}
-
-func (s *AndExprContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitAndExpr(s)
- }
-}
-
-func (p *YqlParser) Expr() (localctx IExprContext) {
- return p.expr(0)
-}
-
-func (p *YqlParser) expr(_p int) (localctx IExprContext) {
- var _parentctx antlr.ParserRuleContext = p.GetParserRuleContext()
- _parentState := p.GetState()
- localctx = NewExprContext(p, p.GetParserRuleContext(), _parentState)
- var _prevctx IExprContext = localctx
- var _ antlr.ParserRuleContext = _prevctx // TODO: To prevent unused variable warning.
- _startState := 2
- p.EnterRecursionRule(localctx, 2, YqlParserRULE_expr, _p)
-
- defer func() {
- p.UnrollRecursionContexts(_parentctx)
- }()
-
- defer func() {
- if err := recover(); err != nil {
- if v, ok := err.(antlr.RecognitionException); ok {
- localctx.SetException(v)
- p.GetErrorHandler().ReportError(p, v)
- p.GetErrorHandler().Recover(p, v)
- } else {
- panic(err)
- }
- }
- }()
-
- var _alt int
-
- p.EnterOuterAlt(localctx, 1)
- p.SetState(18)
- p.GetErrorHandler().Sync(p)
-
- switch p.GetTokenStream().LA(1) {
- case YqlParserFIELDNAME:
- localctx = NewBoolExprContext(p, localctx)
- p.SetParserRuleContext(localctx)
- _prevctx = localctx
-
- {
- p.SetState(13)
- p.BooleanExpr()
- }
-
- case YqlParserT__2:
- localctx = NewEmbbedExprContext(p, localctx)
- p.SetParserRuleContext(localctx)
- _prevctx = localctx
- {
- p.SetState(14)
- p.Match(YqlParserT__2)
- }
- {
- p.SetState(15)
- p.expr(0)
- }
- {
- p.SetState(16)
- p.Match(YqlParserT__3)
- }
-
- default:
- panic(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil))
- }
- p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1))
- p.SetState(28)
- p.GetErrorHandler().Sync(p)
- _alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 2, p.GetParserRuleContext())
-
- for _alt != 2 && _alt != antlr.ATNInvalidAltNumber {
- if _alt == 1 {
- if p.GetParseListeners() != nil {
- p.TriggerExitRuleEvent()
- }
- _prevctx = localctx
- p.SetState(26)
- p.GetErrorHandler().Sync(p)
- switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 1, p.GetParserRuleContext()) {
- case 1:
- localctx = NewAndExprContext(p, NewExprContext(p, _parentctx, _parentState))
- p.PushNewRecursionContext(localctx, _startState, YqlParserRULE_expr)
- p.SetState(20)
-
- if !(p.Precpred(p.GetParserRuleContext(), 3)) {
- panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 3)", ""))
- }
- {
- p.SetState(21)
- p.Match(YqlParserT__0)
- }
- {
- p.SetState(22)
- p.expr(4)
- }
-
- case 2:
- localctx = NewOrExprContext(p, NewExprContext(p, _parentctx, _parentState))
- p.PushNewRecursionContext(localctx, _startState, YqlParserRULE_expr)
- p.SetState(23)
-
- if !(p.Precpred(p.GetParserRuleContext(), 2)) {
- panic(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 2)", ""))
- }
- {
- p.SetState(24)
- p.Match(YqlParserT__1)
- }
- {
- p.SetState(25)
- p.expr(3)
- }
-
- }
-
- }
- p.SetState(30)
- p.GetErrorHandler().Sync(p)
- _alt = p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 2, p.GetParserRuleContext())
- }
-
- return localctx
-}
-
-// IBooleanExprContext is an interface to support dynamic dispatch.
-type IBooleanExprContext interface {
- antlr.ParserRuleContext
-
- // GetParser returns the parser.
- GetParser() antlr.Parser
-
- // GetOp returns the op token.
- GetOp() antlr.Token
-
- // SetOp sets the op token.
- SetOp(antlr.Token)
-
- // IsBooleanExprContext differentiates from other interfaces.
- IsBooleanExprContext()
-}
-
-type BooleanExprContext struct {
- *antlr.BaseParserRuleContext
- parser antlr.Parser
- op antlr.Token
-}
-
-func NewEmptyBooleanExprContext() *BooleanExprContext {
- var p = new(BooleanExprContext)
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(nil, -1)
- p.RuleIndex = YqlParserRULE_booleanExpr
- return p
-}
-
-func (*BooleanExprContext) IsBooleanExprContext() {}
-
-func NewBooleanExprContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *BooleanExprContext {
- var p = new(BooleanExprContext)
-
- p.BaseParserRuleContext = antlr.NewBaseParserRuleContext(parent, invokingState)
-
- p.parser = parser
- p.RuleIndex = YqlParserRULE_booleanExpr
-
- return p
-}
-
-func (s *BooleanExprContext) GetParser() antlr.Parser { return s.parser }
-
-func (s *BooleanExprContext) GetOp() antlr.Token { return s.op }
-
-func (s *BooleanExprContext) SetOp(v antlr.Token) { s.op = v }
-
-func (s *BooleanExprContext) Leftexpr() ILeftexprContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*ILeftexprContext)(nil)).Elem(), 0)
-
- if t == nil {
- return nil
- }
-
- return t.(ILeftexprContext)
-}
-
-func (s *BooleanExprContext) AllValue() []IValueContext {
- var ts = s.GetTypedRuleContexts(reflect.TypeOf((*IValueContext)(nil)).Elem())
- var tst = make([]IValueContext, len(ts))
-
- for i, t := range ts {
- if t != nil {
- tst[i] = t.(IValueContext)
- }
- }
-
- return tst
-}
-
-func (s *BooleanExprContext) Value(i int) IValueContext {
- var t = s.GetTypedRuleContext(reflect.TypeOf((*IValueContext)(nil)).Elem(), i)
-
- if t == nil {
- return nil
- }
-
- return t.(IValueContext)
-}
-
-func (s *BooleanExprContext) GetRuleContext() antlr.RuleContext {
- return s
-}
-
-func (s *BooleanExprContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string {
- return antlr.TreesStringTree(s, ruleNames, recog)
-}
-
-func (s *BooleanExprContext) EnterRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.EnterBooleanExpr(s)
- }
-}
-
-func (s *BooleanExprContext) ExitRule(listener antlr.ParseTreeListener) {
- if listenerT, ok := listener.(YqlListener); ok {
- listenerT.ExitBooleanExpr(s)
- }
-}
-
-func (p *YqlParser) BooleanExpr() (localctx IBooleanExprContext) {
- localctx = NewBooleanExprContext(p, p.GetParserRuleContext(), p.GetState())
- p.EnterRule(localctx, 4, YqlParserRULE_booleanExpr)
- var _la int
-
- defer func() {
- p.ExitRule()
- }()
-
- defer func() {
- if err := recover(); err != nil {
- if v, ok := err.(antlr.RecognitionException); ok {
- localctx.SetException(v)
- p.GetErrorHandler().ReportError(p, v)
- p.GetErrorHandler().Recover(p, v)
- } else {
- panic(err)
- }
- }
- }()
-
- p.SetState(48)
- p.GetErrorHandler().Sync(p)
- switch p.GetInterpreter().AdaptivePredict(p.GetTokenStream(), 4, p.GetParserRuleContext()) {
- case 1:
- p.EnterOuterAlt(localctx, 1)
- {
- p.SetState(31)
- p.Leftexpr()
- }
- p.SetState(32)
-
- var _lt = p.GetTokenStream().LT(1)
-
- localctx.(*BooleanExprContext).op = _lt
-
- _la = p.GetTokenStream().LA(1)
-
- if !(((_la)&-(0x1f+1)) == 0 && ((1< -1 {
- b.sp = -1
- b.data = b.data[:0]
- }
- return b, func() { pool.Put(b) }
-}
-
-var pool = sync.Pool{
- New: func() interface{} {
- return &BoolStack{sp: -1}
- },
-}
diff --git a/vendor/github.com/caibirdme/yql/yql.go b/vendor/github.com/caibirdme/yql/yql.go
deleted file mode 100644
index bb0ffea..0000000
--- a/vendor/github.com/caibirdme/yql/yql.go
+++ /dev/null
@@ -1,226 +0,0 @@
-package yql
-
-import (
- "fmt"
- "strconv"
-
- "github.com/antlr/antlr4/runtime/Go/antlr"
- "github.com/caibirdme/yql/internal/grammar"
- "github.com/caibirdme/yql/internal/stack"
-)
-
-type boolStack interface {
- Push(bool)
- Pop() bool
-}
-
-type yqlListener struct {
- *grammar.BaseYqlListener
- stack boolStack
- data map[string]interface{}
- fieldName string
- funcs []string
- notFoundErr error
-}
-
-func (l *yqlListener) ExitBooleanExpr(ctx *grammar.BooleanExprContext) {
- if l.notFoundErr != nil {
- return
- }
- operator := ctx.GetOp().GetText()
- fieldName := l.fieldName
- actualValue, ok := l.data[fieldName]
- if !ok {
- l.notFoundErr = fmt.Errorf("%s not provided", fieldName)
- return
- }
- var err error
- actualValue, err = funcRuner(actualValue, l.funcs)
- if err != nil {
- l.notFoundErr = err
- return
- }
- allValue := ctx.AllValue()
- valueArr := make([]string, 0, len(allValue))
- for _, v := range allValue {
- valueArr = append(valueArr, v.GetText())
- }
- res := compare(actualValue, valueArr, operator)
- l.stack.Push(res)
-}
-
-func (l *yqlListener) ExitLeftexpr(ctx *grammar.LeftexprContext) {
- l.fieldName = ctx.FIELDNAME().GetText()
- funcs := ctx.AllFUNC()
- l.funcs = l.funcs[:0]
- if 0 == len(funcs) {
- return
- }
- for _, f := range funcs {
- l.funcs = append(l.funcs, f.GetText())
- }
-}
-
-func (l *yqlListener) ExitOrExpr(ctx *grammar.OrExprContext) {
- if l.notFoundErr != nil {
- return
- }
- q1 := l.stack.Pop()
- q2 := l.stack.Pop()
- l.stack.Push(q1 || q2)
-}
-
-func (l *yqlListener) ExitAndExpr(ctx *grammar.AndExprContext) {
- if l.notFoundErr != nil {
- return
- }
- q1 := l.stack.Pop()
- q2 := l.stack.Pop()
- l.stack.Push(q1 && q2)
-}
-
-type bailLexer struct {
- *grammar.YqlLexer
-}
-
-// Override default Recover and do nothing
-// lexer can quit when any error occur
-func (l *bailLexer) Recover(r antlr.RecognitionException) {
- panic(r)
-}
-
-var (
- bailErrStrategy = antlr.NewBailErrorStrategy()
-)
-
-func match(rawYQL string, data map[string]interface{}) (ok bool, err error) {
- if 0 == len(data) {
- return false, nil
- }
- defer func() {
- if r := recover(); nil != r {
- ok = false
- err = fmt.Errorf("%v", r)
- }
- }()
- inputStream := antlr.NewInputStream(rawYQL)
- lexer := &bailLexer{grammar.NewYqlLexer(inputStream)}
- stream := antlr.NewCommonTokenStream(lexer, 0)
- parser := grammar.NewYqlParser(stream)
- parser.BuildParseTrees = true
- parser.RemoveErrorListeners()
- parser.SetErrorHandler(bailErrStrategy)
- tree := parser.Query()
- s, release := stack.NewStack()
- defer release()
- l := &yqlListener{stack: s, funcs: make([]string, 0, 1)}
- l.data = data
- antlr.ParseTreeWalkerDefault.Walk(l, tree)
- if l.notFoundErr != nil {
- return false, l.notFoundErr
- }
- return l.stack.Pop(), nil
-}
-
-// Ruler caches an AST
-type cachedAST struct {
- query grammar.IQueryContext
-}
-
-// Ruler represents an AST structure and could do the match according to input data
-type Ruler interface {
- Match(map[string]interface{}) (bool, error)
-}
-
-// Match do the comparison according to the input data
-func (ast cachedAST) Match(data map[string]interface{}) (bool, error) {
- if 0 == len(data) {
- return false, nil
- }
- s, release := stack.NewStack()
- defer release()
- l := &yqlListener{stack: s, funcs: make([]string, 0, 1)}
- l.data = data
- antlr.ParseTreeWalkerDefault.Walk(l, ast.query)
- if l.notFoundErr != nil {
- return false, l.notFoundErr
- }
- return l.stack.Pop(), nil
-}
-
-// Rule analyze a rule and store the AST
-// it returns error when receives illegal yql expression
-// It's more faster than using Match directly
-func Rule(rawYQL string) (ruler Ruler, err error) {
- ast := cachedAST{}
- defer func() {
- if r := recover(); nil != r {
- err = fmt.Errorf("%v", r)
- ruler = ast
- }
- }()
- inputStream := antlr.NewInputStream(rawYQL)
- lexer := &bailLexer{grammar.NewYqlLexer(inputStream)}
- stream := antlr.NewCommonTokenStream(lexer, 0)
- parser := grammar.NewYqlParser(stream)
- parser.BuildParseTrees = true
- parser.RemoveErrorListeners()
- parser.SetErrorHandler(bailErrStrategy)
- ast.query = parser.Query()
- return ast, nil
-}
-
-// Match interprete the rawYQL and execute it with the provided data
-// error will be returned if rawYQL contains illegal syntax
-func Match(rawYQL string, data map[string]interface{}) (bool, error) {
- return match(rawYQL, data)
-}
-
-func compare(actualValue interface{}, expectValue []string, op string) bool {
- if len(expectValue) > 1 {
- return compareSet(actualValue, expectValue, op)
- }
- e := removeQuote(expectValue[0])
- switch actual := actualValue.(type) {
- case int:
- expect, err := strconv.ParseInt(e, 10, 64)
- if nil != err {
- return false
- }
- return cmpInt(int64(actual), expect, op)
- case int64:
- expect, err := strconv.ParseInt(e, 10, 64)
- if nil != err {
- return false
- }
- return cmpInt(actual, expect, op)
- case float64:
- expect, err := strconv.ParseFloat(e, 64)
- if nil != err {
- return false
- }
- return cmpFloat(actual, expect, op)
- case string:
- return cmpStr(actual, e, op)
- case bool:
- expect, err := strconv.ParseBool(e)
- if nil != err {
- return false
- }
- return cmpBool(actual, expect, op)
- default:
- return false
- }
-}
-
-func removeQuote(str string) string {
- l := 0
- r := len(str)
- if str[0] == '\'' {
- l++
- }
- if str[r-1] == '\'' {
- r--
- }
- return str[l:r]
-}
diff --git a/vendor/github.com/coreos/go-systemd/LICENSE b/vendor/github.com/coreos/go-systemd/LICENSE
deleted file mode 100644
index 37ec93a..0000000
--- a/vendor/github.com/coreos/go-systemd/LICENSE
+++ /dev/null
@@ -1,191 +0,0 @@
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, "control" means (i) the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
-outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-"Object" form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-"submitted" means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-2. Grant of Copyright License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable copyright license to reproduce, prepare Derivative Works of,
-publicly display, publicly perform, sublicense, and distribute the Work and such
-Derivative Works in Source or Object form.
-
-3. Grant of Patent License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable (except as stated in this section) patent license to make, have
-made, use, offer to sell, sell, import, and otherwise transfer the Work, where
-such license applies only to those patent claims licensable by such Contributor
-that are necessarily infringed by their Contribution(s) alone or by combination
-of their Contribution(s) with the Work to which such Contribution(s) was
-submitted. If You institute patent litigation against any entity (including a
-cross-claim or counterclaim in a lawsuit) alleging that the Work or a
-Contribution incorporated within the Work constitutes direct or contributory
-patent infringement, then any patent licenses granted to You under this License
-for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution.
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof
-in any medium, with or without modifications, and in Source or Object form,
-provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any
-Derivative Works that You distribute must include a readable copy of the
-attribution notices contained within such NOTICE file, excluding those notices
-that do not pertain to any part of the Derivative Works, in at least one of the
-following places: within a NOTICE text file distributed as part of the
-Derivative Works; within the Source form or documentation, if provided along
-with the Derivative Works; or, within a display generated by the Derivative
-Works, if and wherever such third-party notices normally appear. The contents of
-the NOTICE file are for informational purposes only and do not modify the
-License. You may add Your own attribution notices within Derivative Works that
-You distribute, alongside or as an addendum to the NOTICE text from the Work,
-provided that such additional attribution notices cannot be construed as
-modifying the License.
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks,
-service marks, or product names of the Licensor, except as required for
-reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the
-Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
-including, without limitation, any warranties or conditions of TITLE,
-NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
-solely responsible for determining the appropriateness of using or
-redistributing the Work and assume any risks associated with Your exercise of
-permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence),
-contract, or otherwise, unless required by applicable law (such as deliberate
-and grossly negligent acts) or agreed to in writing, shall any Contributor be
-liable to You for damages, including any direct, indirect, special, incidental,
-or consequential damages of any character arising as a result of this License or
-out of the use or inability to use the Work (including but not limited to
-damages for loss of goodwill, work stoppage, computer failure or malfunction, or
-any and all other commercial damages or losses), even if such Contributor has
-been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to
-offer, and charge a fee for, acceptance of support, warranty, indemnity, or
-other liability obligations and/or rights consistent with this License. However,
-in accepting such obligations, You may act only on Your own behalf and on Your
-sole responsibility, not on behalf of any other Contributor, and only if You
-agree to indemnify, defend, and hold each Contributor harmless for any liability
-incurred by, or claims asserted against, such Contributor by reason of your
-accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work
-
-To apply the Apache License to your work, attach the following boilerplate
-notice, with the fields enclosed by brackets "[]" replaced with your own
-identifying information. (Don't include the brackets!) The text should be
-enclosed in the appropriate comment syntax for the file format. We also
-recommend that a file or class name and description of purpose be included on
-the same "printed page" as the copyright notice for easier identification within
-third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/coreos/go-systemd/NOTICE b/vendor/github.com/coreos/go-systemd/NOTICE
deleted file mode 100644
index 23a0ada..0000000
--- a/vendor/github.com/coreos/go-systemd/NOTICE
+++ /dev/null
@@ -1,5 +0,0 @@
-CoreOS Project
-Copyright 2018 CoreOS, Inc
-
-This product includes software developed at CoreOS, Inc.
-(http://www.coreos.com/).
diff --git a/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go b/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go
deleted file mode 100644
index ba4ae31..0000000
--- a/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2014 Docker, Inc.
-// Copyright 2015-2018 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// Package daemon provides a Go implementation of the sd_notify protocol.
-// It can be used to inform systemd of service start-up completion, watchdog
-// events, and other status changes.
-//
-// https://www.freedesktop.org/software/systemd/man/sd_notify.html#Description
-package daemon
-
-import (
- "net"
- "os"
-)
-
-const (
- // SdNotifyReady tells the service manager that service startup is finished
- // or the service finished loading its configuration.
- SdNotifyReady = "READY=1"
-
- // SdNotifyStopping tells the service manager that the service is beginning
- // its shutdown.
- SdNotifyStopping = "STOPPING=1"
-
- // SdNotifyReloading tells the service manager that this service is
- // reloading its configuration. Note that you must call SdNotifyReady when
- // it completed reloading.
- SdNotifyReloading = "RELOADING=1"
-
- // SdNotifyWatchdog tells the service manager to update the watchdog
- // timestamp for the service.
- SdNotifyWatchdog = "WATCHDOG=1"
-)
-
-// SdNotify sends a message to the init daemon. It is common to ignore the error.
-// If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET`
-// will be unconditionally unset.
-//
-// It returns one of the following:
-// (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset)
-// (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data)
-// (true, nil) - notification supported, data has been sent
-func SdNotify(unsetEnvironment bool, state string) (bool, error) {
- socketAddr := &net.UnixAddr{
- Name: os.Getenv("NOTIFY_SOCKET"),
- Net: "unixgram",
- }
-
- // NOTIFY_SOCKET not set
- if socketAddr.Name == "" {
- return false, nil
- }
-
- if unsetEnvironment {
- if err := os.Unsetenv("NOTIFY_SOCKET"); err != nil {
- return false, err
- }
- }
-
- conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
- // Error connecting to NOTIFY_SOCKET
- if err != nil {
- return false, err
- }
- defer conn.Close()
-
- if _, err = conn.Write([]byte(state)); err != nil {
- return false, err
- }
- return true, nil
-}
diff --git a/vendor/github.com/coreos/go-systemd/daemon/watchdog.go b/vendor/github.com/coreos/go-systemd/daemon/watchdog.go
deleted file mode 100644
index 7a0e0d3..0000000
--- a/vendor/github.com/coreos/go-systemd/daemon/watchdog.go
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2016 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package daemon
-
-import (
- "fmt"
- "os"
- "strconv"
- "time"
-)
-
-// SdWatchdogEnabled returns watchdog information for a service.
-// Processes should call daemon.SdNotify(false, daemon.SdNotifyWatchdog) every
-// time / 2.
-// If `unsetEnvironment` is true, the environment variables `WATCHDOG_USEC` and
-// `WATCHDOG_PID` will be unconditionally unset.
-//
-// It returns one of the following:
-// (0, nil) - watchdog isn't enabled or we aren't the watched PID.
-// (0, err) - an error happened (e.g. error converting time).
-// (time, nil) - watchdog is enabled and we can send ping.
-// time is delay before inactive service will be killed.
-func SdWatchdogEnabled(unsetEnvironment bool) (time.Duration, error) {
- wusec := os.Getenv("WATCHDOG_USEC")
- wpid := os.Getenv("WATCHDOG_PID")
- if unsetEnvironment {
- wusecErr := os.Unsetenv("WATCHDOG_USEC")
- wpidErr := os.Unsetenv("WATCHDOG_PID")
- if wusecErr != nil {
- return 0, wusecErr
- }
- if wpidErr != nil {
- return 0, wpidErr
- }
- }
-
- if wusec == "" {
- return 0, nil
- }
- s, err := strconv.Atoi(wusec)
- if err != nil {
- return 0, fmt.Errorf("error converting WATCHDOG_USEC: %s", err)
- }
- if s <= 0 {
- return 0, fmt.Errorf("error WATCHDOG_USEC must be a positive number")
- }
- interval := time.Duration(s) * time.Microsecond
-
- if wpid == "" {
- return interval, nil
- }
- p, err := strconv.Atoi(wpid)
- if err != nil {
- return 0, fmt.Errorf("error converting WATCHDOG_PID: %s", err)
- }
- if os.Getpid() != p {
- return 0, nil
- }
-
- return interval, nil
-}
diff --git a/vendor/github.com/go-ini/ini/.gitignore b/vendor/github.com/go-ini/ini/.gitignore
deleted file mode 100644
index 1241112..0000000
--- a/vendor/github.com/go-ini/ini/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-testdata/conf_out.ini
-ini.sublime-project
-ini.sublime-workspace
-testdata/conf_reflect.ini
-.idea
-/.vscode
diff --git a/vendor/github.com/go-ini/ini/.travis.yml b/vendor/github.com/go-ini/ini/.travis.yml
deleted file mode 100644
index c8ea49c..0000000
--- a/vendor/github.com/go-ini/ini/.travis.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-sudo: false
-language: go
-go:
- - 1.6.x
- - 1.7.x
- - 1.8.x
- - 1.9.x
- - 1.10.x
- - 1.11.x
-
-script:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/smartystreets/goconvey
- - mkdir -p $HOME/gopath/src/gopkg.in
- - ln -s $HOME/gopath/src/github.com/go-ini/ini $HOME/gopath/src/gopkg.in/ini.v1
- - cd $HOME/gopath/src/gopkg.in/ini.v1
- - go test -v -cover -race
diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE
deleted file mode 100644
index d361bbc..0000000
--- a/vendor/github.com/go-ini/ini/LICENSE
+++ /dev/null
@@ -1,191 +0,0 @@
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, "control" means (i) the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
-outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-"Object" form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-"submitted" means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-2. Grant of Copyright License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable copyright license to reproduce, prepare Derivative Works of,
-publicly display, publicly perform, sublicense, and distribute the Work and such
-Derivative Works in Source or Object form.
-
-3. Grant of Patent License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable (except as stated in this section) patent license to make, have
-made, use, offer to sell, sell, import, and otherwise transfer the Work, where
-such license applies only to those patent claims licensable by such Contributor
-that are necessarily infringed by their Contribution(s) alone or by combination
-of their Contribution(s) with the Work to which such Contribution(s) was
-submitted. If You institute patent litigation against any entity (including a
-cross-claim or counterclaim in a lawsuit) alleging that the Work or a
-Contribution incorporated within the Work constitutes direct or contributory
-patent infringement, then any patent licenses granted to You under this License
-for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution.
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof
-in any medium, with or without modifications, and in Source or Object form,
-provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any
-Derivative Works that You distribute must include a readable copy of the
-attribution notices contained within such NOTICE file, excluding those notices
-that do not pertain to any part of the Derivative Works, in at least one of the
-following places: within a NOTICE text file distributed as part of the
-Derivative Works; within the Source form or documentation, if provided along
-with the Derivative Works; or, within a display generated by the Derivative
-Works, if and wherever such third-party notices normally appear. The contents of
-the NOTICE file are for informational purposes only and do not modify the
-License. You may add Your own attribution notices within Derivative Works that
-You distribute, alongside or as an addendum to the NOTICE text from the Work,
-provided that such additional attribution notices cannot be construed as
-modifying the License.
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks,
-service marks, or product names of the Licensor, except as required for
-reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the
-Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
-including, without limitation, any warranties or conditions of TITLE,
-NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
-solely responsible for determining the appropriateness of using or
-redistributing the Work and assume any risks associated with Your exercise of
-permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence),
-contract, or otherwise, unless required by applicable law (such as deliberate
-and grossly negligent acts) or agreed to in writing, shall any Contributor be
-liable to You for damages, including any direct, indirect, special, incidental,
-or consequential damages of any character arising as a result of this License or
-out of the use or inability to use the Work (including but not limited to
-damages for loss of goodwill, work stoppage, computer failure or malfunction, or
-any and all other commercial damages or losses), even if such Contributor has
-been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to
-offer, and charge a fee for, acceptance of support, warranty, indemnity, or
-other liability obligations and/or rights consistent with this License. However,
-in accepting such obligations, You may act only on Your own behalf and on Your
-sole responsibility, not on behalf of any other Contributor, and only if You
-agree to indemnify, defend, and hold each Contributor harmless for any liability
-incurred by, or claims asserted against, such Contributor by reason of your
-accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work
-
-To apply the Apache License to your work, attach the following boilerplate
-notice, with the fields enclosed by brackets "[]" replaced with your own
-identifying information. (Don't include the brackets!) The text should be
-enclosed in the appropriate comment syntax for the file format. We also
-recommend that a file or class name and description of purpose be included on
-the same "printed page" as the copyright notice for easier identification within
-third-party archives.
-
- Copyright 2014 Unknwon
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile
deleted file mode 100644
index af27ff0..0000000
--- a/vendor/github.com/go-ini/ini/Makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-.PHONY: build test bench vet coverage
-
-build: vet bench
-
-test:
- go test -v -cover -race
-
-bench:
- go test -v -cover -race -test.bench=. -test.benchmem
-
-vet:
- go vet
-
-coverage:
- go test -coverprofile=c.out && go tool cover -html=c.out && rm c.out
diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md
deleted file mode 100644
index ae4dfc3..0000000
--- a/vendor/github.com/go-ini/ini/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-INI [](https://travis-ci.org/go-ini/ini) [](https://sourcegraph.com/github.com/go-ini/ini)
-===
-
-
-
-Package ini provides INI file read and write functionality in Go.
-
-## Features
-
-- Load from multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites.
-- Read with recursion values.
-- Read with parent-child sections.
-- Read with auto-increment key names.
-- Read with multiple-line values.
-- Read with tons of helper methods.
-- Read and convert values to Go types.
-- Read and **WRITE** comments of sections and keys.
-- Manipulate sections, keys and comments with ease.
-- Keep sections and keys in order as you parse and save.
-
-## Installation
-
-The minimum requirement of Go is **1.6**.
-
-To use a tagged revision:
-
-```sh
-$ go get gopkg.in/ini.v1
-```
-
-To use with latest changes:
-
-```sh
-$ go get github.com/go-ini/ini
-```
-
-Please add `-u` flag to update in the future.
-
-## Getting Help
-
-- [Getting Started](https://ini.unknwon.io/docs/intro/getting_started)
-- [API Documentation](https://gowalker.org/gopkg.in/ini.v1)
-
-## License
-
-This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text.
diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go
deleted file mode 100644
index 80afe74..0000000
--- a/vendor/github.com/go-ini/ini/error.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2016 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "fmt"
-)
-
-type ErrDelimiterNotFound struct {
- Line string
-}
-
-func IsErrDelimiterNotFound(err error) bool {
- _, ok := err.(ErrDelimiterNotFound)
- return ok
-}
-
-func (err ErrDelimiterNotFound) Error() string {
- return fmt.Sprintf("key-value delimiter not found: %s", err.Line)
-}
diff --git a/vendor/github.com/go-ini/ini/file.go b/vendor/github.com/go-ini/ini/file.go
deleted file mode 100644
index 0ed0eaf..0000000
--- a/vendor/github.com/go-ini/ini/file.go
+++ /dev/null
@@ -1,418 +0,0 @@
-// Copyright 2017 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "strings"
- "sync"
-)
-
-// File represents a combination of a or more INI file(s) in memory.
-type File struct {
- options LoadOptions
- dataSources []dataSource
-
- // Should make things safe, but sometimes doesn't matter.
- BlockMode bool
- lock sync.RWMutex
-
- // To keep data in order.
- sectionList []string
- // Actual data is stored here.
- sections map[string]*Section
-
- NameMapper
- ValueMapper
-}
-
-// newFile initializes File object with given data sources.
-func newFile(dataSources []dataSource, opts LoadOptions) *File {
- if len(opts.KeyValueDelimiters) == 0 {
- opts.KeyValueDelimiters = "=:"
- }
- return &File{
- BlockMode: true,
- dataSources: dataSources,
- sections: make(map[string]*Section),
- sectionList: make([]string, 0, 10),
- options: opts,
- }
-}
-
-// Empty returns an empty file object.
-func Empty() *File {
- // Ignore error here, we sure our data is good.
- f, _ := Load([]byte(""))
- return f
-}
-
-// NewSection creates a new section.
-func (f *File) NewSection(name string) (*Section, error) {
- if len(name) == 0 {
- return nil, errors.New("error creating new section: empty section name")
- } else if f.options.Insensitive && name != DEFAULT_SECTION {
- name = strings.ToLower(name)
- }
-
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
-
- if inSlice(name, f.sectionList) {
- return f.sections[name], nil
- }
-
- f.sectionList = append(f.sectionList, name)
- f.sections[name] = newSection(f, name)
- return f.sections[name], nil
-}
-
-// NewRawSection creates a new section with an unparseable body.
-func (f *File) NewRawSection(name, body string) (*Section, error) {
- section, err := f.NewSection(name)
- if err != nil {
- return nil, err
- }
-
- section.isRawSection = true
- section.rawBody = body
- return section, nil
-}
-
-// NewSections creates a list of sections.
-func (f *File) NewSections(names ...string) (err error) {
- for _, name := range names {
- if _, err = f.NewSection(name); err != nil {
- return err
- }
- }
- return nil
-}
-
-// GetSection returns section by given name.
-func (f *File) GetSection(name string) (*Section, error) {
- if len(name) == 0 {
- name = DEFAULT_SECTION
- }
- if f.options.Insensitive {
- name = strings.ToLower(name)
- }
-
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
-
- sec := f.sections[name]
- if sec == nil {
- return nil, fmt.Errorf("section '%s' does not exist", name)
- }
- return sec, nil
-}
-
-// Section assumes named section exists and returns a zero-value when not.
-func (f *File) Section(name string) *Section {
- sec, err := f.GetSection(name)
- if err != nil {
- // Note: It's OK here because the only possible error is empty section name,
- // but if it's empty, this piece of code won't be executed.
- sec, _ = f.NewSection(name)
- return sec
- }
- return sec
-}
-
-// Section returns list of Section.
-func (f *File) Sections() []*Section {
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
-
- sections := make([]*Section, len(f.sectionList))
- for i, name := range f.sectionList {
- sections[i] = f.sections[name]
- }
- return sections
-}
-
-// ChildSections returns a list of child sections of given section name.
-func (f *File) ChildSections(name string) []*Section {
- return f.Section(name).ChildSections()
-}
-
-// SectionStrings returns list of section names.
-func (f *File) SectionStrings() []string {
- list := make([]string, len(f.sectionList))
- copy(list, f.sectionList)
- return list
-}
-
-// DeleteSection deletes a section.
-func (f *File) DeleteSection(name string) {
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
-
- if len(name) == 0 {
- name = DEFAULT_SECTION
- }
-
- for i, s := range f.sectionList {
- if s == name {
- f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
- delete(f.sections, name)
- return
- }
- }
-}
-
-func (f *File) reload(s dataSource) error {
- r, err := s.ReadCloser()
- if err != nil {
- return err
- }
- defer r.Close()
-
- return f.parse(r)
-}
-
-// Reload reloads and parses all data sources.
-func (f *File) Reload() (err error) {
- for _, s := range f.dataSources {
- if err = f.reload(s); err != nil {
- // In loose mode, we create an empty default section for nonexistent files.
- if os.IsNotExist(err) && f.options.Loose {
- f.parse(bytes.NewBuffer(nil))
- continue
- }
- return err
- }
- }
- return nil
-}
-
-// Append appends one or more data sources and reloads automatically.
-func (f *File) Append(source interface{}, others ...interface{}) error {
- ds, err := parseDataSource(source)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- for _, s := range others {
- ds, err = parseDataSource(s)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- }
- return f.Reload()
-}
-
-func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
- equalSign := DefaultFormatLeft + "=" + DefaultFormatRight
-
- if PrettyFormat || PrettyEqual {
- equalSign = " = "
- }
-
- // Use buffer to make sure target is safe until finish encoding.
- buf := bytes.NewBuffer(nil)
- for i, sname := range f.sectionList {
- sec := f.Section(sname)
- if len(sec.Comment) > 0 {
- // Support multiline comments
- lines := strings.Split(sec.Comment, LineBreak)
- for i := range lines {
- if lines[i][0] != '#' && lines[i][0] != ';' {
- lines[i] = "; " + lines[i]
- } else {
- lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
- }
-
- if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
- return nil, err
- }
- }
- }
-
- if i > 0 || DefaultHeader {
- if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
- return nil, err
- }
- } else {
- // Write nothing if default section is empty
- if len(sec.keyList) == 0 {
- continue
- }
- }
-
- if sec.isRawSection {
- if _, err := buf.WriteString(sec.rawBody); err != nil {
- return nil, err
- }
-
- if PrettySection {
- // Put a line between sections
- if _, err := buf.WriteString(LineBreak); err != nil {
- return nil, err
- }
- }
- continue
- }
-
- // Count and generate alignment length and buffer spaces using the
- // longest key. Keys may be modifed if they contain certain characters so
- // we need to take that into account in our calculation.
- alignLength := 0
- if PrettyFormat {
- for _, kname := range sec.keyList {
- keyLength := len(kname)
- // First case will surround key by ` and second by """
- if strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters) {
- keyLength += 2
- } else if strings.Contains(kname, "`") {
- keyLength += 6
- }
-
- if keyLength > alignLength {
- alignLength = keyLength
- }
- }
- }
- alignSpaces := bytes.Repeat([]byte(" "), alignLength)
-
- KEY_LIST:
- for _, kname := range sec.keyList {
- key := sec.Key(kname)
- if len(key.Comment) > 0 {
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
-
- // Support multiline comments
- lines := strings.Split(key.Comment, LineBreak)
- for i := range lines {
- if lines[i][0] != '#' && lines[i][0] != ';' {
- lines[i] = "; " + strings.TrimSpace(lines[i])
- } else {
- lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
- }
-
- if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
- return nil, err
- }
- }
- }
-
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
-
- switch {
- case key.isAutoIncrement:
- kname = "-"
- case strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters):
- kname = "`" + kname + "`"
- case strings.Contains(kname, "`"):
- kname = `"""` + kname + `"""`
- }
-
- for _, val := range key.ValueWithShadows() {
- if _, err := buf.WriteString(kname); err != nil {
- return nil, err
- }
-
- if key.isBooleanType {
- if kname != sec.keyList[len(sec.keyList)-1] {
- buf.WriteString(LineBreak)
- }
- continue KEY_LIST
- }
-
- // Write out alignment spaces before "=" sign
- if PrettyFormat {
- buf.Write(alignSpaces[:alignLength-len(kname)])
- }
-
- // In case key value contains "\n", "`", "\"", "#" or ";"
- if strings.ContainsAny(val, "\n`") {
- val = `"""` + val + `"""`
- } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") {
- val = "`" + val + "`"
- }
- if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil {
- return nil, err
- }
- }
-
- for _, val := range key.nestedValues {
- if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil {
- return nil, err
- }
- }
- }
-
- if PrettySection {
- // Put a line between sections
- if _, err := buf.WriteString(LineBreak); err != nil {
- return nil, err
- }
- }
- }
-
- return buf, nil
-}
-
-// WriteToIndent writes content into io.Writer with given indention.
-// If PrettyFormat has been set to be true,
-// it will align "=" sign with spaces under each section.
-func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) {
- buf, err := f.writeToBuffer(indent)
- if err != nil {
- return 0, err
- }
- return buf.WriteTo(w)
-}
-
-// WriteTo writes file content into io.Writer.
-func (f *File) WriteTo(w io.Writer) (int64, error) {
- return f.WriteToIndent(w, "")
-}
-
-// SaveToIndent writes content to file system with given value indention.
-func (f *File) SaveToIndent(filename, indent string) error {
- // Note: Because we are truncating with os.Create,
- // so it's safer to save to a temporary file location and rename afte done.
- buf, err := f.writeToBuffer(indent)
- if err != nil {
- return err
- }
-
- return ioutil.WriteFile(filename, buf.Bytes(), 0666)
-}
-
-// SaveTo writes content to file system.
-func (f *File) SaveTo(filename string) error {
- return f.SaveToIndent(filename, "")
-}
diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go
deleted file mode 100644
index f827a1e..0000000
--- a/vendor/github.com/go-ini/ini/ini.go
+++ /dev/null
@@ -1,219 +0,0 @@
-// +build go1.6
-
-// Copyright 2014 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-// Package ini provides INI file read and write functionality in Go.
-package ini
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "regexp"
- "runtime"
-)
-
-const (
- // Name for default section. You can use this constant or the string literal.
- // In most of cases, an empty string is all you need to access the section.
- DEFAULT_SECTION = "DEFAULT"
-
- // Maximum allowed depth when recursively substituing variable names.
- _DEPTH_VALUES = 99
- _VERSION = "1.42.0"
-)
-
-// Version returns current package version literal.
-func Version() string {
- return _VERSION
-}
-
-var (
- // Delimiter to determine or compose a new line.
- // This variable will be changed to "\r\n" automatically on Windows
- // at package init time.
- LineBreak = "\n"
-
- // Place custom spaces when PrettyFormat and PrettyEqual are both disabled
- DefaultFormatLeft = ""
- DefaultFormatRight = ""
-
- // Variable regexp pattern: %(variable)s
- varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
-
- // Indicate whether to align "=" sign with spaces to produce pretty output
- // or reduce all possible spaces for compact format.
- PrettyFormat = true
-
- // Place spaces around "=" sign even when PrettyFormat is false
- PrettyEqual = false
-
- // Explicitly write DEFAULT section header
- DefaultHeader = false
-
- // Indicate whether to put a line between sections
- PrettySection = true
-)
-
-func init() {
- if runtime.GOOS == "windows" {
- LineBreak = "\r\n"
- }
-}
-
-func inSlice(str string, s []string) bool {
- for _, v := range s {
- if str == v {
- return true
- }
- }
- return false
-}
-
-// dataSource is an interface that returns object which can be read and closed.
-type dataSource interface {
- ReadCloser() (io.ReadCloser, error)
-}
-
-// sourceFile represents an object that contains content on the local file system.
-type sourceFile struct {
- name string
-}
-
-func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
- return os.Open(s.name)
-}
-
-// sourceData represents an object that contains content in memory.
-type sourceData struct {
- data []byte
-}
-
-func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(s.data)), nil
-}
-
-// sourceReadCloser represents an input stream with Close method.
-type sourceReadCloser struct {
- reader io.ReadCloser
-}
-
-func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
- return s.reader, nil
-}
-
-func parseDataSource(source interface{}) (dataSource, error) {
- switch s := source.(type) {
- case string:
- return sourceFile{s}, nil
- case []byte:
- return &sourceData{s}, nil
- case io.ReadCloser:
- return &sourceReadCloser{s}, nil
- default:
- return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
- }
-}
-
-type LoadOptions struct {
- // Loose indicates whether the parser should ignore nonexistent files or return error.
- Loose bool
- // Insensitive indicates whether the parser forces all section and key names to lowercase.
- Insensitive bool
- // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
- IgnoreContinuation bool
- // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
- IgnoreInlineComment bool
- // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
- SkipUnrecognizableLines bool
- // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
- // This type of keys are mostly used in my.cnf.
- AllowBooleanKeys bool
- // AllowShadows indicates whether to keep track of keys with same name under same section.
- AllowShadows bool
- // AllowNestedValues indicates whether to allow AWS-like nested values.
- // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
- AllowNestedValues bool
- // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
- // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
- // Relevant quote: Values can also span multiple lines, as long as they are indented deeper
- // than the first line of the value.
- AllowPythonMultilineValues bool
- // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
- // Docs: https://docs.python.org/2/library/configparser.html
- // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
- // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
- SpaceBeforeInlineComment bool
- // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
- // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
- UnescapeValueDoubleQuotes bool
- // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
- // when value is NOT surrounded by any quotes.
- // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
- UnescapeValueCommentSymbols bool
- // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
- // conform to key/value pairs. Specify the names of those blocks here.
- UnparseableSections []string
- // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
- KeyValueDelimiters string
- // PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
- PreserveSurroundedQuote bool
-}
-
-func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
- sources := make([]dataSource, len(others)+1)
- sources[0], err = parseDataSource(source)
- if err != nil {
- return nil, err
- }
- for i := range others {
- sources[i+1], err = parseDataSource(others[i])
- if err != nil {
- return nil, err
- }
- }
- f := newFile(sources, opts)
- if err = f.Reload(); err != nil {
- return nil, err
- }
- return f, nil
-}
-
-// Load loads and parses from INI data sources.
-// Arguments can be mixed of file name with string type, or raw data in []byte.
-// It will return error if list contains nonexistent files.
-func Load(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{}, source, others...)
-}
-
-// LooseLoad has exactly same functionality as Load function
-// except it ignores nonexistent files instead of returning error.
-func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Loose: true}, source, others...)
-}
-
-// InsensitiveLoad has exactly same functionality as Load function
-// except it forces all section and key names to be lowercased.
-func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Insensitive: true}, source, others...)
-}
-
-// ShadowLoad has exactly same functionality as Load function
-// except it allows have shadow keys.
-func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
-}
diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go
deleted file mode 100644
index 0fee0dc..0000000
--- a/vendor/github.com/go-ini/ini/key.go
+++ /dev/null
@@ -1,752 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "bytes"
- "errors"
- "fmt"
- "strconv"
- "strings"
- "time"
-)
-
-// Key represents a key under a section.
-type Key struct {
- s *Section
- Comment string
- name string
- value string
- isAutoIncrement bool
- isBooleanType bool
-
- isShadow bool
- shadows []*Key
-
- nestedValues []string
-}
-
-// newKey simply return a key object with given values.
-func newKey(s *Section, name, val string) *Key {
- return &Key{
- s: s,
- name: name,
- value: val,
- }
-}
-
-func (k *Key) addShadow(val string) error {
- if k.isShadow {
- return errors.New("cannot add shadow to another shadow key")
- } else if k.isAutoIncrement || k.isBooleanType {
- return errors.New("cannot add shadow to auto-increment or boolean key")
- }
-
- shadow := newKey(k.s, k.name, val)
- shadow.isShadow = true
- k.shadows = append(k.shadows, shadow)
- return nil
-}
-
-// AddShadow adds a new shadow key to itself.
-func (k *Key) AddShadow(val string) error {
- if !k.s.f.options.AllowShadows {
- return errors.New("shadow key is not allowed")
- }
- return k.addShadow(val)
-}
-
-func (k *Key) addNestedValue(val string) error {
- if k.isAutoIncrement || k.isBooleanType {
- return errors.New("cannot add nested value to auto-increment or boolean key")
- }
-
- k.nestedValues = append(k.nestedValues, val)
- return nil
-}
-
-func (k *Key) AddNestedValue(val string) error {
- if !k.s.f.options.AllowNestedValues {
- return errors.New("nested value is not allowed")
- }
- return k.addNestedValue(val)
-}
-
-// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
-type ValueMapper func(string) string
-
-// Name returns name of key.
-func (k *Key) Name() string {
- return k.name
-}
-
-// Value returns raw value of key for performance purpose.
-func (k *Key) Value() string {
- return k.value
-}
-
-// ValueWithShadows returns raw values of key and its shadows if any.
-func (k *Key) ValueWithShadows() []string {
- if len(k.shadows) == 0 {
- return []string{k.value}
- }
- vals := make([]string, len(k.shadows)+1)
- vals[0] = k.value
- for i := range k.shadows {
- vals[i+1] = k.shadows[i].value
- }
- return vals
-}
-
-// NestedValues returns nested values stored in the key.
-// It is possible returned value is nil if no nested values stored in the key.
-func (k *Key) NestedValues() []string {
- return k.nestedValues
-}
-
-// transformValue takes a raw value and transforms to its final string.
-func (k *Key) transformValue(val string) string {
- if k.s.f.ValueMapper != nil {
- val = k.s.f.ValueMapper(val)
- }
-
- // Fail-fast if no indicate char found for recursive value
- if !strings.Contains(val, "%") {
- return val
- }
- for i := 0; i < _DEPTH_VALUES; i++ {
- vr := varPattern.FindString(val)
- if len(vr) == 0 {
- break
- }
-
- // Take off leading '%(' and trailing ')s'.
- noption := vr[2 : len(vr)-2]
-
- // Search in the same section.
- nk, err := k.s.GetKey(noption)
- if err != nil || k == nk {
- // Search again in default section.
- nk, _ = k.s.f.Section("").GetKey(noption)
- }
-
- // Substitute by new value and take off leading '%(' and trailing ')s'.
- val = strings.Replace(val, vr, nk.value, -1)
- }
- return val
-}
-
-// String returns string representation of value.
-func (k *Key) String() string {
- return k.transformValue(k.value)
-}
-
-// Validate accepts a validate function which can
-// return modifed result as key value.
-func (k *Key) Validate(fn func(string) string) string {
- return fn(k.String())
-}
-
-// parseBool returns the boolean value represented by the string.
-//
-// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
-// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
-// Any other value returns an error.
-func parseBool(str string) (value bool, err error) {
- switch str {
- case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
- return true, nil
- case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
- return false, nil
- }
- return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
-}
-
-// Bool returns bool type value.
-func (k *Key) Bool() (bool, error) {
- return parseBool(k.String())
-}
-
-// Float64 returns float64 type value.
-func (k *Key) Float64() (float64, error) {
- return strconv.ParseFloat(k.String(), 64)
-}
-
-// Int returns int type value.
-func (k *Key) Int() (int, error) {
- v, err := strconv.ParseInt(k.String(), 0, 64)
- return int(v), err
-}
-
-// Int64 returns int64 type value.
-func (k *Key) Int64() (int64, error) {
- return strconv.ParseInt(k.String(), 0, 64)
-}
-
-// Uint returns uint type valued.
-func (k *Key) Uint() (uint, error) {
- u, e := strconv.ParseUint(k.String(), 0, 64)
- return uint(u), e
-}
-
-// Uint64 returns uint64 type value.
-func (k *Key) Uint64() (uint64, error) {
- return strconv.ParseUint(k.String(), 0, 64)
-}
-
-// Duration returns time.Duration type value.
-func (k *Key) Duration() (time.Duration, error) {
- return time.ParseDuration(k.String())
-}
-
-// TimeFormat parses with given format and returns time.Time type value.
-func (k *Key) TimeFormat(format string) (time.Time, error) {
- return time.Parse(format, k.String())
-}
-
-// Time parses with RFC3339 format and returns time.Time type value.
-func (k *Key) Time() (time.Time, error) {
- return k.TimeFormat(time.RFC3339)
-}
-
-// MustString returns default value if key value is empty.
-func (k *Key) MustString(defaultVal string) string {
- val := k.String()
- if len(val) == 0 {
- k.value = defaultVal
- return defaultVal
- }
- return val
-}
-
-// MustBool always returns value without error,
-// it returns false if error occurs.
-func (k *Key) MustBool(defaultVal ...bool) bool {
- val, err := k.Bool()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatBool(defaultVal[0])
- return defaultVal[0]
- }
- return val
-}
-
-// MustFloat64 always returns value without error,
-// it returns 0.0 if error occurs.
-func (k *Key) MustFloat64(defaultVal ...float64) float64 {
- val, err := k.Float64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
- return defaultVal[0]
- }
- return val
-}
-
-// MustInt always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustInt(defaultVal ...int) int {
- val, err := k.Int()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustInt64 always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustInt64(defaultVal ...int64) int64 {
- val, err := k.Int64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatInt(defaultVal[0], 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustUint always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustUint(defaultVal ...uint) uint {
- val, err := k.Uint()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustUint64 always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
- val, err := k.Uint64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatUint(defaultVal[0], 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustDuration always returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
- val, err := k.Duration()
- if len(defaultVal) > 0 && err != nil {
- k.value = defaultVal[0].String()
- return defaultVal[0]
- }
- return val
-}
-
-// MustTimeFormat always parses with given format and returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
- val, err := k.TimeFormat(format)
- if len(defaultVal) > 0 && err != nil {
- k.value = defaultVal[0].Format(format)
- return defaultVal[0]
- }
- return val
-}
-
-// MustTime always parses with RFC3339 format and returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
- return k.MustTimeFormat(time.RFC3339, defaultVal...)
-}
-
-// In always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) In(defaultVal string, candidates []string) string {
- val := k.String()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InFloat64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
- val := k.MustFloat64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InInt always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InInt(defaultVal int, candidates []int) int {
- val := k.MustInt()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InInt64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
- val := k.MustInt64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InUint always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
- val := k.MustUint()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InUint64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
- val := k.MustUint64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InTimeFormat always parses with given format and returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
- val := k.MustTimeFormat(format)
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InTime always parses with RFC3339 format and returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
- return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
-}
-
-// RangeFloat64 checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
- val := k.MustFloat64()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeInt checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeInt(defaultVal, min, max int) int {
- val := k.MustInt()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeInt64 checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
- val := k.MustInt64()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeTimeFormat checks if value with given format is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
- val := k.MustTimeFormat(format)
- if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
- return defaultVal
- }
- return val
-}
-
-// RangeTime checks if value with RFC3339 format is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
- return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
-}
-
-// Strings returns list of string divided by given delimiter.
-func (k *Key) Strings(delim string) []string {
- str := k.String()
- if len(str) == 0 {
- return []string{}
- }
-
- runes := []rune(str)
- vals := make([]string, 0, 2)
- var buf bytes.Buffer
- escape := false
- idx := 0
- for {
- if escape {
- escape = false
- if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) {
- buf.WriteRune('\\')
- }
- buf.WriteRune(runes[idx])
- } else {
- if runes[idx] == '\\' {
- escape = true
- } else if strings.HasPrefix(string(runes[idx:]), delim) {
- idx += len(delim) - 1
- vals = append(vals, strings.TrimSpace(buf.String()))
- buf.Reset()
- } else {
- buf.WriteRune(runes[idx])
- }
- }
- idx += 1
- if idx == len(runes) {
- break
- }
- }
-
- if buf.Len() > 0 {
- vals = append(vals, strings.TrimSpace(buf.String()))
- }
-
- return vals
-}
-
-// StringsWithShadows returns list of string divided by given delimiter.
-// Shadows will also be appended if any.
-func (k *Key) StringsWithShadows(delim string) []string {
- vals := k.ValueWithShadows()
- results := make([]string, 0, len(vals)*2)
- for i := range vals {
- if len(vals) == 0 {
- continue
- }
-
- results = append(results, strings.Split(vals[i], delim)...)
- }
-
- for i := range results {
- results[i] = k.transformValue(strings.TrimSpace(results[i]))
- }
- return results
-}
-
-// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Float64s(delim string) []float64 {
- vals, _ := k.parseFloat64s(k.Strings(delim), true, false)
- return vals
-}
-
-// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Ints(delim string) []int {
- vals, _ := k.parseInts(k.Strings(delim), true, false)
- return vals
-}
-
-// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Int64s(delim string) []int64 {
- vals, _ := k.parseInt64s(k.Strings(delim), true, false)
- return vals
-}
-
-// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Uints(delim string) []uint {
- vals, _ := k.parseUints(k.Strings(delim), true, false)
- return vals
-}
-
-// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Uint64s(delim string) []uint64 {
- vals, _ := k.parseUint64s(k.Strings(delim), true, false)
- return vals
-}
-
-// TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
-// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
-func (k *Key) TimesFormat(format, delim string) []time.Time {
- vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false)
- return vals
-}
-
-// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
-// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
-func (k *Key) Times(delim string) []time.Time {
- return k.TimesFormat(time.RFC3339, delim)
-}
-
-// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
-// it will not be included to result list.
-func (k *Key) ValidFloat64s(delim string) []float64 {
- vals, _ := k.parseFloat64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
-// not be included to result list.
-func (k *Key) ValidInts(delim string) []int {
- vals, _ := k.parseInts(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
-// then it will not be included to result list.
-func (k *Key) ValidInt64s(delim string) []int64 {
- vals, _ := k.parseInt64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
-// then it will not be included to result list.
-func (k *Key) ValidUints(delim string) []uint {
- vals, _ := k.parseUints(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
-// integer, then it will not be included to result list.
-func (k *Key) ValidUint64s(delim string) []uint64 {
- vals, _ := k.parseUint64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
-func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
- vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false)
- return vals
-}
-
-// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
-func (k *Key) ValidTimes(delim string) []time.Time {
- return k.ValidTimesFormat(time.RFC3339, delim)
-}
-
-// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
- return k.parseFloat64s(k.Strings(delim), false, true)
-}
-
-// StrictInts returns list of int divided by given delimiter or error on first invalid input.
-func (k *Key) StrictInts(delim string) ([]int, error) {
- return k.parseInts(k.Strings(delim), false, true)
-}
-
-// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictInt64s(delim string) ([]int64, error) {
- return k.parseInt64s(k.Strings(delim), false, true)
-}
-
-// StrictUints returns list of uint divided by given delimiter or error on first invalid input.
-func (k *Key) StrictUints(delim string) ([]uint, error) {
- return k.parseUints(k.Strings(delim), false, true)
-}
-
-// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
- return k.parseUint64s(k.Strings(delim), false, true)
-}
-
-// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
-// or error on first invalid input.
-func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
- return k.parseTimesFormat(format, k.Strings(delim), false, true)
-}
-
-// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
-// or error on first invalid input.
-func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
- return k.StrictTimesFormat(time.RFC3339, delim)
-}
-
-// parseFloat64s transforms strings to float64s.
-func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) {
- vals := make([]float64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseFloat(str, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseInts transforms strings to ints.
-func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
- vals := make([]int, 0, len(strs))
- for _, str := range strs {
- valInt64, err := strconv.ParseInt(str, 0, 64)
- val := int(valInt64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseInt64s transforms strings to int64s.
-func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
- vals := make([]int64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseInt(str, 0, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseUints transforms strings to uints.
-func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) {
- vals := make([]uint, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseUint(str, 0, 0)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, uint(val))
- }
- }
- return vals, nil
-}
-
-// parseUint64s transforms strings to uint64s.
-func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
- vals := make([]uint64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseUint(str, 0, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseTimesFormat transforms strings to times in given format.
-func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
- vals := make([]time.Time, 0, len(strs))
- for _, str := range strs {
- val, err := time.Parse(format, str)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// SetValue changes key value.
-func (k *Key) SetValue(v string) {
- if k.s.f.BlockMode {
- k.s.f.lock.Lock()
- defer k.s.f.lock.Unlock()
- }
-
- k.value = v
- k.s.keysHash[k.name] = v
-}
diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go
deleted file mode 100644
index f20073d..0000000
--- a/vendor/github.com/go-ini/ini/parser.go
+++ /dev/null
@@ -1,488 +0,0 @@
-// Copyright 2015 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io"
- "regexp"
- "strconv"
- "strings"
- "unicode"
-)
-
-var pythonMultiline = regexp.MustCompile("^(\\s+)([^\n]+)")
-
-type tokenType int
-
-const (
- _TOKEN_INVALID tokenType = iota
- _TOKEN_COMMENT
- _TOKEN_SECTION
- _TOKEN_KEY
-)
-
-type parser struct {
- buf *bufio.Reader
- isEOF bool
- count int
- comment *bytes.Buffer
-}
-
-func newParser(r io.Reader) *parser {
- return &parser{
- buf: bufio.NewReader(r),
- count: 1,
- comment: &bytes.Buffer{},
- }
-}
-
-// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format.
-// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
-func (p *parser) BOM() error {
- mask, err := p.buf.Peek(2)
- if err != nil && err != io.EOF {
- return err
- } else if len(mask) < 2 {
- return nil
- }
-
- switch {
- case mask[0] == 254 && mask[1] == 255:
- fallthrough
- case mask[0] == 255 && mask[1] == 254:
- p.buf.Read(mask)
- case mask[0] == 239 && mask[1] == 187:
- mask, err := p.buf.Peek(3)
- if err != nil && err != io.EOF {
- return err
- } else if len(mask) < 3 {
- return nil
- }
- if mask[2] == 191 {
- p.buf.Read(mask)
- }
- }
- return nil
-}
-
-func (p *parser) readUntil(delim byte) ([]byte, error) {
- data, err := p.buf.ReadBytes(delim)
- if err != nil {
- if err == io.EOF {
- p.isEOF = true
- } else {
- return nil, err
- }
- }
- return data, nil
-}
-
-func cleanComment(in []byte) ([]byte, bool) {
- i := bytes.IndexAny(in, "#;")
- if i == -1 {
- return nil, false
- }
- return in[i:], true
-}
-
-func readKeyName(delimiters string, in []byte) (string, int, error) {
- line := string(in)
-
- // Check if key name surrounded by quotes.
- var keyQuote string
- if line[0] == '"' {
- if len(line) > 6 && string(line[0:3]) == `"""` {
- keyQuote = `"""`
- } else {
- keyQuote = `"`
- }
- } else if line[0] == '`' {
- keyQuote = "`"
- }
-
- // Get out key name
- endIdx := -1
- if len(keyQuote) > 0 {
- startIdx := len(keyQuote)
- // FIXME: fail case -> """"""name"""=value
- pos := strings.Index(line[startIdx:], keyQuote)
- if pos == -1 {
- return "", -1, fmt.Errorf("missing closing key quote: %s", line)
- }
- pos += startIdx
-
- // Find key-value delimiter
- i := strings.IndexAny(line[pos+startIdx:], delimiters)
- if i < 0 {
- return "", -1, ErrDelimiterNotFound{line}
- }
- endIdx = pos + i
- return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil
- }
-
- endIdx = strings.IndexAny(line, delimiters)
- if endIdx < 0 {
- return "", -1, ErrDelimiterNotFound{line}
- }
- return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
-}
-
-func (p *parser) readMultilines(line, val, valQuote string) (string, error) {
- for {
- data, err := p.readUntil('\n')
- if err != nil {
- return "", err
- }
- next := string(data)
-
- pos := strings.LastIndex(next, valQuote)
- if pos > -1 {
- val += next[:pos]
-
- comment, has := cleanComment([]byte(next[pos:]))
- if has {
- p.comment.Write(bytes.TrimSpace(comment))
- }
- break
- }
- val += next
- if p.isEOF {
- return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next)
- }
- }
- return val, nil
-}
-
-func (p *parser) readContinuationLines(val string) (string, error) {
- for {
- data, err := p.readUntil('\n')
- if err != nil {
- return "", err
- }
- next := strings.TrimSpace(string(data))
-
- if len(next) == 0 {
- break
- }
- val += next
- if val[len(val)-1] != '\\' {
- break
- }
- val = val[:len(val)-1]
- }
- return val, nil
-}
-
-// hasSurroundedQuote check if and only if the first and last characters
-// are quotes \" or \'.
-// It returns false if any other parts also contain same kind of quotes.
-func hasSurroundedQuote(in string, quote byte) bool {
- return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote &&
- strings.IndexByte(in[1:], quote) == len(in)-2
-}
-
-func (p *parser) readValue(in []byte,
- parserBufferSize int,
- ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols, allowPythonMultilines, spaceBeforeInlineComment, preserveSurroundedQuote bool) (string, error) {
-
- line := strings.TrimLeftFunc(string(in), unicode.IsSpace)
- if len(line) == 0 {
- return "", nil
- }
-
- var valQuote string
- if len(line) > 3 && string(line[0:3]) == `"""` {
- valQuote = `"""`
- } else if line[0] == '`' {
- valQuote = "`"
- } else if unescapeValueDoubleQuotes && line[0] == '"' {
- valQuote = `"`
- }
-
- if len(valQuote) > 0 {
- startIdx := len(valQuote)
- pos := strings.LastIndex(line[startIdx:], valQuote)
- // Check for multi-line value
- if pos == -1 {
- return p.readMultilines(line, line[startIdx:], valQuote)
- }
-
- if unescapeValueDoubleQuotes && valQuote == `"` {
- return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil
- }
- return line[startIdx : pos+startIdx], nil
- }
-
- lastChar := line[len(line)-1]
- // Won't be able to reach here if value only contains whitespace
- line = strings.TrimSpace(line)
- trimmedLastChar := line[len(line)-1]
-
- // Check continuation lines when desired
- if !ignoreContinuation && trimmedLastChar == '\\' {
- return p.readContinuationLines(line[:len(line)-1])
- }
-
- // Check if ignore inline comment
- if !ignoreInlineComment {
- var i int
- if spaceBeforeInlineComment {
- i = strings.Index(line, " #")
- if i == -1 {
- i = strings.Index(line, " ;")
- }
-
- } else {
- i = strings.IndexAny(line, "#;")
- }
-
- if i > -1 {
- p.comment.WriteString(line[i:])
- line = strings.TrimSpace(line[:i])
- }
-
- }
-
- // Trim single and double quotes
- if (hasSurroundedQuote(line, '\'') ||
- hasSurroundedQuote(line, '"')) && !preserveSurroundedQuote {
- line = line[1 : len(line)-1]
- } else if len(valQuote) == 0 && unescapeValueCommentSymbols {
- if strings.Contains(line, `\;`) {
- line = strings.Replace(line, `\;`, ";", -1)
- }
- if strings.Contains(line, `\#`) {
- line = strings.Replace(line, `\#`, "#", -1)
- }
- } else if allowPythonMultilines && lastChar == '\n' {
- parserBufferPeekResult, _ := p.buf.Peek(parserBufferSize)
- peekBuffer := bytes.NewBuffer(parserBufferPeekResult)
-
- val := line
-
- for {
- peekData, peekErr := peekBuffer.ReadBytes('\n')
- if peekErr != nil {
- if peekErr == io.EOF {
- return val, nil
- }
- return "", peekErr
- }
-
- peekMatches := pythonMultiline.FindStringSubmatch(string(peekData))
- if len(peekMatches) != 3 {
- return val, nil
- }
-
- // NOTE: Return if not a python-ini multi-line value.
- currentIdentSize := len(peekMatches[1])
- if currentIdentSize <= 0 {
- return val, nil
- }
-
- // NOTE: Just advance the parser reader (buffer) in-sync with the peek buffer.
- _, err := p.readUntil('\n')
- if err != nil {
- return "", err
- }
-
- val += fmt.Sprintf("\n%s", peekMatches[2])
- }
- }
-
- return line, nil
-}
-
-// parse parses data through an io.Reader.
-func (f *File) parse(reader io.Reader) (err error) {
- p := newParser(reader)
- if err = p.BOM(); err != nil {
- return fmt.Errorf("BOM: %v", err)
- }
-
- // Ignore error because default section name is never empty string.
- name := DEFAULT_SECTION
- if f.options.Insensitive {
- name = strings.ToLower(DEFAULT_SECTION)
- }
- section, _ := f.NewSection(name)
-
- // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key
- var isLastValueEmpty bool
- var lastRegularKey *Key
-
- var line []byte
- var inUnparseableSection bool
-
- // NOTE: Iterate and increase `currentPeekSize` until
- // the size of the parser buffer is found.
- // TODO(unknwon): When Golang 1.10 is the lowest version supported, replace with `parserBufferSize := p.buf.Size()`.
- parserBufferSize := 0
- // NOTE: Peek 1kb at a time.
- currentPeekSize := 1024
-
- if f.options.AllowPythonMultilineValues {
- for {
- peekBytes, _ := p.buf.Peek(currentPeekSize)
- peekBytesLength := len(peekBytes)
-
- if parserBufferSize >= peekBytesLength {
- break
- }
-
- currentPeekSize *= 2
- parserBufferSize = peekBytesLength
- }
- }
-
- for !p.isEOF {
- line, err = p.readUntil('\n')
- if err != nil {
- return err
- }
-
- if f.options.AllowNestedValues &&
- isLastValueEmpty && len(line) > 0 {
- if line[0] == ' ' || line[0] == '\t' {
- lastRegularKey.addNestedValue(string(bytes.TrimSpace(line)))
- continue
- }
- }
-
- line = bytes.TrimLeftFunc(line, unicode.IsSpace)
- if len(line) == 0 {
- continue
- }
-
- // Comments
- if line[0] == '#' || line[0] == ';' {
- // Note: we do not care ending line break,
- // it is needed for adding second line,
- // so just clean it once at the end when set to value.
- p.comment.Write(line)
- continue
- }
-
- // Section
- if line[0] == '[' {
- // Read to the next ']' (TODO: support quoted strings)
- closeIdx := bytes.LastIndexByte(line, ']')
- if closeIdx == -1 {
- return fmt.Errorf("unclosed section: %s", line)
- }
-
- name := string(line[1:closeIdx])
- section, err = f.NewSection(name)
- if err != nil {
- return err
- }
-
- comment, has := cleanComment(line[closeIdx+1:])
- if has {
- p.comment.Write(comment)
- }
-
- section.Comment = strings.TrimSpace(p.comment.String())
-
- // Reset aotu-counter and comments
- p.comment.Reset()
- p.count = 1
-
- inUnparseableSection = false
- for i := range f.options.UnparseableSections {
- if f.options.UnparseableSections[i] == name ||
- (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) {
- inUnparseableSection = true
- continue
- }
- }
- continue
- }
-
- if inUnparseableSection {
- section.isRawSection = true
- section.rawBody += string(line)
- continue
- }
-
- kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line)
- if err != nil {
- // Treat as boolean key when desired, and whole line is key name.
- if IsErrDelimiterNotFound(err) {
- switch {
- case f.options.AllowBooleanKeys:
- kname, err := p.readValue(line,
- parserBufferSize,
- f.options.IgnoreContinuation,
- f.options.IgnoreInlineComment,
- f.options.UnescapeValueDoubleQuotes,
- f.options.UnescapeValueCommentSymbols,
- f.options.AllowPythonMultilineValues,
- f.options.SpaceBeforeInlineComment,
- f.options.PreserveSurroundedQuote)
- if err != nil {
- return err
- }
- key, err := section.NewBooleanKey(kname)
- if err != nil {
- return err
- }
- key.Comment = strings.TrimSpace(p.comment.String())
- p.comment.Reset()
- continue
-
- case f.options.SkipUnrecognizableLines:
- continue
- }
- }
- return err
- }
-
- // Auto increment.
- isAutoIncr := false
- if kname == "-" {
- isAutoIncr = true
- kname = "#" + strconv.Itoa(p.count)
- p.count++
- }
-
- value, err := p.readValue(line[offset:],
- parserBufferSize,
- f.options.IgnoreContinuation,
- f.options.IgnoreInlineComment,
- f.options.UnescapeValueDoubleQuotes,
- f.options.UnescapeValueCommentSymbols,
- f.options.AllowPythonMultilineValues,
- f.options.SpaceBeforeInlineComment,
- f.options.PreserveSurroundedQuote)
- if err != nil {
- return err
- }
- isLastValueEmpty = len(value) == 0
-
- key, err := section.NewKey(kname, value)
- if err != nil {
- return err
- }
- key.isAutoIncrement = isAutoIncr
- key.Comment = strings.TrimSpace(p.comment.String())
- p.comment.Reset()
- lastRegularKey = key
- }
- return nil
-}
diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go
deleted file mode 100644
index bc32c62..0000000
--- a/vendor/github.com/go-ini/ini/section.go
+++ /dev/null
@@ -1,259 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "errors"
- "fmt"
- "strings"
-)
-
-// Section represents a config section.
-type Section struct {
- f *File
- Comment string
- name string
- keys map[string]*Key
- keyList []string
- keysHash map[string]string
-
- isRawSection bool
- rawBody string
-}
-
-func newSection(f *File, name string) *Section {
- return &Section{
- f: f,
- name: name,
- keys: make(map[string]*Key),
- keyList: make([]string, 0, 10),
- keysHash: make(map[string]string),
- }
-}
-
-// Name returns name of Section.
-func (s *Section) Name() string {
- return s.name
-}
-
-// Body returns rawBody of Section if the section was marked as unparseable.
-// It still follows the other rules of the INI format surrounding leading/trailing whitespace.
-func (s *Section) Body() string {
- return strings.TrimSpace(s.rawBody)
-}
-
-// SetBody updates body content only if section is raw.
-func (s *Section) SetBody(body string) {
- if !s.isRawSection {
- return
- }
- s.rawBody = body
-}
-
-// NewKey creates a new key to given section.
-func (s *Section) NewKey(name, val string) (*Key, error) {
- if len(name) == 0 {
- return nil, errors.New("error creating new key: empty key name")
- } else if s.f.options.Insensitive {
- name = strings.ToLower(name)
- }
-
- if s.f.BlockMode {
- s.f.lock.Lock()
- defer s.f.lock.Unlock()
- }
-
- if inSlice(name, s.keyList) {
- if s.f.options.AllowShadows {
- if err := s.keys[name].addShadow(val); err != nil {
- return nil, err
- }
- } else {
- s.keys[name].value = val
- s.keysHash[name] = val
- }
- return s.keys[name], nil
- }
-
- s.keyList = append(s.keyList, name)
- s.keys[name] = newKey(s, name, val)
- s.keysHash[name] = val
- return s.keys[name], nil
-}
-
-// NewBooleanKey creates a new boolean type key to given section.
-func (s *Section) NewBooleanKey(name string) (*Key, error) {
- key, err := s.NewKey(name, "true")
- if err != nil {
- return nil, err
- }
-
- key.isBooleanType = true
- return key, nil
-}
-
-// GetKey returns key in section by given name.
-func (s *Section) GetKey(name string) (*Key, error) {
- // FIXME: change to section level lock?
- if s.f.BlockMode {
- s.f.lock.RLock()
- }
- if s.f.options.Insensitive {
- name = strings.ToLower(name)
- }
- key := s.keys[name]
- if s.f.BlockMode {
- s.f.lock.RUnlock()
- }
-
- if key == nil {
- // Check if it is a child-section.
- sname := s.name
- for {
- if i := strings.LastIndex(sname, "."); i > -1 {
- sname = sname[:i]
- sec, err := s.f.GetSection(sname)
- if err != nil {
- continue
- }
- return sec.GetKey(name)
- } else {
- break
- }
- }
- return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name)
- }
- return key, nil
-}
-
-// HasKey returns true if section contains a key with given name.
-func (s *Section) HasKey(name string) bool {
- key, _ := s.GetKey(name)
- return key != nil
-}
-
-// Haskey is a backwards-compatible name for HasKey.
-// TODO: delete me in v2
-func (s *Section) Haskey(name string) bool {
- return s.HasKey(name)
-}
-
-// HasValue returns true if section contains given raw value.
-func (s *Section) HasValue(value string) bool {
- if s.f.BlockMode {
- s.f.lock.RLock()
- defer s.f.lock.RUnlock()
- }
-
- for _, k := range s.keys {
- if value == k.value {
- return true
- }
- }
- return false
-}
-
-// Key assumes named Key exists in section and returns a zero-value when not.
-func (s *Section) Key(name string) *Key {
- key, err := s.GetKey(name)
- if err != nil {
- // It's OK here because the only possible error is empty key name,
- // but if it's empty, this piece of code won't be executed.
- key, _ = s.NewKey(name, "")
- return key
- }
- return key
-}
-
-// Keys returns list of keys of section.
-func (s *Section) Keys() []*Key {
- keys := make([]*Key, len(s.keyList))
- for i := range s.keyList {
- keys[i] = s.Key(s.keyList[i])
- }
- return keys
-}
-
-// ParentKeys returns list of keys of parent section.
-func (s *Section) ParentKeys() []*Key {
- var parentKeys []*Key
- sname := s.name
- for {
- if i := strings.LastIndex(sname, "."); i > -1 {
- sname = sname[:i]
- sec, err := s.f.GetSection(sname)
- if err != nil {
- continue
- }
- parentKeys = append(parentKeys, sec.Keys()...)
- } else {
- break
- }
-
- }
- return parentKeys
-}
-
-// KeyStrings returns list of key names of section.
-func (s *Section) KeyStrings() []string {
- list := make([]string, len(s.keyList))
- copy(list, s.keyList)
- return list
-}
-
-// KeysHash returns keys hash consisting of names and values.
-func (s *Section) KeysHash() map[string]string {
- if s.f.BlockMode {
- s.f.lock.RLock()
- defer s.f.lock.RUnlock()
- }
-
- hash := map[string]string{}
- for key, value := range s.keysHash {
- hash[key] = value
- }
- return hash
-}
-
-// DeleteKey deletes a key from section.
-func (s *Section) DeleteKey(name string) {
- if s.f.BlockMode {
- s.f.lock.Lock()
- defer s.f.lock.Unlock()
- }
-
- for i, k := range s.keyList {
- if k == name {
- s.keyList = append(s.keyList[:i], s.keyList[i+1:]...)
- delete(s.keys, name)
- delete(s.keysHash, name)
- return
- }
- }
-}
-
-// ChildSections returns a list of child sections of current section.
-// For example, "[parent.child1]" and "[parent.child12]" are child sections
-// of section "[parent]".
-func (s *Section) ChildSections() []*Section {
- prefix := s.name + "."
- children := make([]*Section, 0, 3)
- for _, name := range s.f.sectionList {
- if strings.HasPrefix(name, prefix) {
- children = append(children, s.f.sections[name])
- }
- }
- return children
-}
diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go
deleted file mode 100644
index a9dfed0..0000000
--- a/vendor/github.com/go-ini/ini/struct.go
+++ /dev/null
@@ -1,512 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
-// not use this file except in compliance with the License. You may obtain
-// a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations
-// under the License.
-
-package ini
-
-import (
- "bytes"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "time"
- "unicode"
-)
-
-// NameMapper represents a ini tag name mapper.
-type NameMapper func(string) string
-
-// Built-in name getters.
-var (
- // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE.
- AllCapsUnderscore NameMapper = func(raw string) string {
- newstr := make([]rune, 0, len(raw))
- for i, chr := range raw {
- if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
- if i > 0 {
- newstr = append(newstr, '_')
- }
- }
- newstr = append(newstr, unicode.ToUpper(chr))
- }
- return string(newstr)
- }
- // TitleUnderscore converts to format title_underscore.
- TitleUnderscore NameMapper = func(raw string) string {
- newstr := make([]rune, 0, len(raw))
- for i, chr := range raw {
- if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
- if i > 0 {
- newstr = append(newstr, '_')
- }
- chr -= ('A' - 'a')
- }
- newstr = append(newstr, chr)
- }
- return string(newstr)
- }
-)
-
-func (s *Section) parseFieldName(raw, actual string) string {
- if len(actual) > 0 {
- return actual
- }
- if s.f.NameMapper != nil {
- return s.f.NameMapper(raw)
- }
- return raw
-}
-
-func parseDelim(actual string) string {
- if len(actual) > 0 {
- return actual
- }
- return ","
-}
-
-var reflectTime = reflect.TypeOf(time.Now()).Kind()
-
-// setSliceWithProperType sets proper values to slice based on its type.
-func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
- var strs []string
- if allowShadow {
- strs = key.StringsWithShadows(delim)
- } else {
- strs = key.Strings(delim)
- }
-
- numVals := len(strs)
- if numVals == 0 {
- return nil
- }
-
- var vals interface{}
- var err error
-
- sliceOf := field.Type().Elem().Kind()
- switch sliceOf {
- case reflect.String:
- vals = strs
- case reflect.Int:
- vals, err = key.parseInts(strs, true, false)
- case reflect.Int64:
- vals, err = key.parseInt64s(strs, true, false)
- case reflect.Uint:
- vals, err = key.parseUints(strs, true, false)
- case reflect.Uint64:
- vals, err = key.parseUint64s(strs, true, false)
- case reflect.Float64:
- vals, err = key.parseFloat64s(strs, true, false)
- case reflectTime:
- vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false)
- default:
- return fmt.Errorf("unsupported type '[]%s'", sliceOf)
- }
- if err != nil && isStrict {
- return err
- }
-
- slice := reflect.MakeSlice(field.Type(), numVals, numVals)
- for i := 0; i < numVals; i++ {
- switch sliceOf {
- case reflect.String:
- slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i]))
- case reflect.Int:
- slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i]))
- case reflect.Int64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i]))
- case reflect.Uint:
- slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i]))
- case reflect.Uint64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i]))
- case reflect.Float64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i]))
- case reflectTime:
- slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i]))
- }
- }
- field.Set(slice)
- return nil
-}
-
-func wrapStrictError(err error, isStrict bool) error {
- if isStrict {
- return err
- }
- return nil
-}
-
-// setWithProperType sets proper value to field based on its type,
-// but it does not return error for failing parsing,
-// because we want to use default value that is already assigned to strcut.
-func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
- switch t.Kind() {
- case reflect.String:
- if len(key.String()) == 0 {
- return nil
- }
- field.SetString(key.String())
- case reflect.Bool:
- boolVal, err := key.Bool()
- if err != nil {
- return wrapStrictError(err, isStrict)
- }
- field.SetBool(boolVal)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- durationVal, err := key.Duration()
- // Skip zero value
- if err == nil && int64(durationVal) > 0 {
- field.Set(reflect.ValueOf(durationVal))
- return nil
- }
-
- intVal, err := key.Int64()
- if err != nil {
- return wrapStrictError(err, isStrict)
- }
- field.SetInt(intVal)
- // byte is an alias for uint8, so supporting uint8 breaks support for byte
- case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- durationVal, err := key.Duration()
- // Skip zero value
- if err == nil && uint64(durationVal) > 0 {
- field.Set(reflect.ValueOf(durationVal))
- return nil
- }
-
- uintVal, err := key.Uint64()
- if err != nil {
- return wrapStrictError(err, isStrict)
- }
- field.SetUint(uintVal)
-
- case reflect.Float32, reflect.Float64:
- floatVal, err := key.Float64()
- if err != nil {
- return wrapStrictError(err, isStrict)
- }
- field.SetFloat(floatVal)
- case reflectTime:
- timeVal, err := key.Time()
- if err != nil {
- return wrapStrictError(err, isStrict)
- }
- field.Set(reflect.ValueOf(timeVal))
- case reflect.Slice:
- return setSliceWithProperType(key, field, delim, allowShadow, isStrict)
- default:
- return fmt.Errorf("unsupported type '%s'", t)
- }
- return nil
-}
-
-func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) {
- opts := strings.SplitN(tag, ",", 3)
- rawName = opts[0]
- if len(opts) > 1 {
- omitEmpty = opts[1] == "omitempty"
- }
- if len(opts) > 2 {
- allowShadow = opts[2] == "allowshadow"
- }
- return rawName, omitEmpty, allowShadow
-}
-
-func (s *Section) mapTo(val reflect.Value, isStrict bool) error {
- if val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- typ := val.Type()
-
- for i := 0; i < typ.NumField(); i++ {
- field := val.Field(i)
- tpField := typ.Field(i)
-
- tag := tpField.Tag.Get("ini")
- if tag == "-" {
- continue
- }
-
- rawName, _, allowShadow := parseTagOptions(tag)
- fieldName := s.parseFieldName(tpField.Name, rawName)
- if len(fieldName) == 0 || !field.CanSet() {
- continue
- }
-
- isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
- isStruct := tpField.Type.Kind() == reflect.Struct
- if isAnonymous {
- field.Set(reflect.New(tpField.Type.Elem()))
- }
-
- if isAnonymous || isStruct {
- if sec, err := s.f.GetSection(fieldName); err == nil {
- if err = sec.mapTo(field, isStrict); err != nil {
- return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
- }
- continue
- }
- }
-
- if key, err := s.GetKey(fieldName); err == nil {
- delim := parseDelim(tpField.Tag.Get("delim"))
- if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil {
- return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
- }
- }
- }
- return nil
-}
-
-// MapTo maps section to given struct.
-func (s *Section) MapTo(v interface{}) error {
- typ := reflect.TypeOf(v)
- val := reflect.ValueOf(v)
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- val = val.Elem()
- } else {
- return errors.New("cannot map to non-pointer struct")
- }
-
- return s.mapTo(val, false)
-}
-
-// MapTo maps section to given struct in strict mode,
-// which returns all possible error including value parsing error.
-func (s *Section) StrictMapTo(v interface{}) error {
- typ := reflect.TypeOf(v)
- val := reflect.ValueOf(v)
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- val = val.Elem()
- } else {
- return errors.New("cannot map to non-pointer struct")
- }
-
- return s.mapTo(val, true)
-}
-
-// MapTo maps file to given struct.
-func (f *File) MapTo(v interface{}) error {
- return f.Section("").MapTo(v)
-}
-
-// MapTo maps file to given struct in strict mode,
-// which returns all possible error including value parsing error.
-func (f *File) StrictMapTo(v interface{}) error {
- return f.Section("").StrictMapTo(v)
-}
-
-// MapTo maps data sources to given struct with name mapper.
-func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
- cfg, err := Load(source, others...)
- if err != nil {
- return err
- }
- cfg.NameMapper = mapper
- return cfg.MapTo(v)
-}
-
-// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode,
-// which returns all possible error including value parsing error.
-func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
- cfg, err := Load(source, others...)
- if err != nil {
- return err
- }
- cfg.NameMapper = mapper
- return cfg.StrictMapTo(v)
-}
-
-// MapTo maps data sources to given struct.
-func MapTo(v, source interface{}, others ...interface{}) error {
- return MapToWithMapper(v, nil, source, others...)
-}
-
-// StrictMapTo maps data sources to given struct in strict mode,
-// which returns all possible error including value parsing error.
-func StrictMapTo(v, source interface{}, others ...interface{}) error {
- return StrictMapToWithMapper(v, nil, source, others...)
-}
-
-// reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
-func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error {
- slice := field.Slice(0, field.Len())
- if field.Len() == 0 {
- return nil
- }
-
- var buf bytes.Buffer
- sliceOf := field.Type().Elem().Kind()
- for i := 0; i < field.Len(); i++ {
- switch sliceOf {
- case reflect.String:
- buf.WriteString(slice.Index(i).String())
- case reflect.Int, reflect.Int64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Int()))
- case reflect.Uint, reflect.Uint64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Uint()))
- case reflect.Float64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Float()))
- case reflectTime:
- buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339))
- default:
- return fmt.Errorf("unsupported type '[]%s'", sliceOf)
- }
- buf.WriteString(delim)
- }
- key.SetValue(buf.String()[:buf.Len()-1])
- return nil
-}
-
-// reflectWithProperType does the opposite thing as setWithProperType.
-func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
- switch t.Kind() {
- case reflect.String:
- key.SetValue(field.String())
- case reflect.Bool:
- key.SetValue(fmt.Sprint(field.Bool()))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- key.SetValue(fmt.Sprint(field.Int()))
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- key.SetValue(fmt.Sprint(field.Uint()))
- case reflect.Float32, reflect.Float64:
- key.SetValue(fmt.Sprint(field.Float()))
- case reflectTime:
- key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339)))
- case reflect.Slice:
- return reflectSliceWithProperType(key, field, delim)
- default:
- return fmt.Errorf("unsupported type '%s'", t)
- }
- return nil
-}
-
-// CR: copied from encoding/json/encode.go with modifications of time.Time support.
-// TODO: add more test coverage.
-func isEmptyValue(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
- return v.Len() == 0
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.Interface, reflect.Ptr:
- return v.IsNil()
- case reflectTime:
- t, ok := v.Interface().(time.Time)
- return ok && t.IsZero()
- }
- return false
-}
-
-func (s *Section) reflectFrom(val reflect.Value) error {
- if val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- typ := val.Type()
-
- for i := 0; i < typ.NumField(); i++ {
- field := val.Field(i)
- tpField := typ.Field(i)
-
- tag := tpField.Tag.Get("ini")
- if tag == "-" {
- continue
- }
-
- opts := strings.SplitN(tag, ",", 2)
- if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) {
- continue
- }
-
- fieldName := s.parseFieldName(tpField.Name, opts[0])
- if len(fieldName) == 0 || !field.CanSet() {
- continue
- }
-
- if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
- (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") {
- // Note: The only error here is section doesn't exist.
- sec, err := s.f.GetSection(fieldName)
- if err != nil {
- // Note: fieldName can never be empty here, ignore error.
- sec, _ = s.f.NewSection(fieldName)
- }
-
- // Add comment from comment tag
- if len(sec.Comment) == 0 {
- sec.Comment = tpField.Tag.Get("comment")
- }
-
- if err = sec.reflectFrom(field); err != nil {
- return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
- }
- continue
- }
-
- // Note: Same reason as secion.
- key, err := s.GetKey(fieldName)
- if err != nil {
- key, _ = s.NewKey(fieldName, "")
- }
-
- // Add comment from comment tag
- if len(key.Comment) == 0 {
- key.Comment = tpField.Tag.Get("comment")
- }
-
- if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
- return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
- }
-
- }
- return nil
-}
-
-// ReflectFrom reflects secion from given struct.
-func (s *Section) ReflectFrom(v interface{}) error {
- typ := reflect.TypeOf(v)
- val := reflect.ValueOf(v)
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- val = val.Elem()
- } else {
- return errors.New("cannot reflect from non-pointer struct")
- }
-
- return s.reflectFrom(val)
-}
-
-// ReflectFrom reflects file from given struct.
-func (f *File) ReflectFrom(v interface{}) error {
- return f.Section("").ReflectFrom(v)
-}
-
-// ReflectFrom reflects data sources from given struct with name mapper.
-func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
- cfg.NameMapper = mapper
- return cfg.ReflectFrom(v)
-}
-
-// ReflectFrom reflects data sources from given struct.
-func ReflectFrom(cfg *File, v interface{}) error {
- return ReflectFromWithMapper(cfg, v, nil)
-}
diff --git a/vendor/github.com/go-xorm/xorm/.drone.yml b/vendor/github.com/go-xorm/xorm/.drone.yml
deleted file mode 100644
index df9d405..0000000
--- a/vendor/github.com/go-xorm/xorm/.drone.yml
+++ /dev/null
@@ -1,125 +0,0 @@
-workspace:
- base: /go
- path: src/github.com/go-xorm/xorm
-
-clone:
- git:
- image: plugins/git:next
- depth: 50
- tags: true
-
-services:
- mysql:
- image: mysql:5.7
- environment:
- - MYSQL_DATABASE=xorm_test
- - MYSQL_ALLOW_EMPTY_PASSWORD=yes
- when:
- event: [ push, tag, pull_request ]
-
- pgsql:
- image: postgres:9.5
- environment:
- - POSTGRES_USER=postgres
- - POSTGRES_DB=xorm_test
- when:
- event: [ push, tag, pull_request ]
-
- #mssql:
- # image: microsoft/mssql-server-linux:2017-CU11
- # environment:
- # - ACCEPT_EULA=Y
- # - SA_PASSWORD=yourStrong(!)Password
- # - MSSQL_PID=Developer
- # commands:
- # - echo 'CREATE DATABASE xorm_test' > create.sql
- # - /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P yourStrong(!)Password -i "create.sql"
-
-matrix:
- GO_VERSION:
- - 1.8
- - 1.9
- - 1.10
- - 1.11
-
-pipeline:
- init_postgres:
- image: postgres:9.5
- commands:
- # wait for postgres service to become available
- - |
- until psql -U postgres -d xorm_test -h pgsql \
- -c "SELECT 1;" >/dev/null 2>&1; do sleep 1; done
- # query the database
- - |
- psql -U postgres -d xorm_test -h pgsql \
- -c "create schema xorm;"
-
- build:
- image: golang:${GO_VERSION}
- commands:
- - go get -t -d -v ./...
- - go get -u xorm.io/core
- - go get -u xorm.io/builder
- - go build -v
- when:
- event: [ push, pull_request ]
-
- test-sqlite:
- image: golang:${GO_VERSION}
- commands:
- - go get -u github.com/wadey/gocovmerge
- - go test -v -race -db="sqlite3" -conn_str="./test.db" -coverprofile=coverage1-1.txt -covermode=atomic
- - go test -v -race -db="sqlite3" -conn_str="./test.db" -cache=true -coverprofile=coverage1-2.txt -covermode=atomic
- when:
- event: [ push, pull_request ]
-
- test-mysql:
- image: golang:${GO_VERSION}
- commands:
- - go test -v -race -db="mysql" -conn_str="root:@tcp(mysql)/xorm_test" -coverprofile=coverage2-1.txt -covermode=atomic
- - go test -v -race -db="mysql" -conn_str="root:@tcp(mysql)/xorm_test" -cache=true -coverprofile=coverage2-2.txt -covermode=atomic
- when:
- event: [ push, pull_request ]
-
- test-mysql-utf8mb4:
- image: golang:${GO_VERSION}
- commands:
- - go test -v -race -db="mysql" -conn_str="root:@tcp(mysql)/xorm_test?charset=utf8mb4" -coverprofile=coverage2.1-1.txt -covermode=atomic
- - go test -v -race -db="mysql" -conn_str="root:@tcp(mysql)/xorm_test?charset=utf8mb4" -cache=true -coverprofile=coverage2.1-2.txt -covermode=atomic
- when:
- event: [ push, pull_request ]
-
- test-mymysql:
- image: golang:${GO_VERSION}
- commands:
- - go test -v -race -db="mymysql" -conn_str="tcp:mysql:3306*xorm_test/root/" -coverprofile=coverage3-1.txt -covermode=atomic
- - go test -v -race -db="mymysql" -conn_str="tcp:mysql:3306*xorm_test/root/" -cache=true -coverprofile=coverage3-2.txt -covermode=atomic
- when:
- event: [ push, pull_request ]
-
- test-postgres:
- image: golang:${GO_VERSION}
- commands:
- - go test -v -race -db="postgres" -conn_str="postgres://postgres:@pgsql/xorm_test?sslmode=disable" -coverprofile=coverage4-1.txt -covermode=atomic
- - go test -v -race -db="postgres" -conn_str="postgres://postgres:@pgsql/xorm_test?sslmode=disable" -cache=true -coverprofile=coverage4-2.txt -covermode=atomic
- when:
- event: [ push, pull_request ]
-
- test-postgres-schema:
- image: golang:${GO_VERSION}
- commands:
- - go test -v -race -db="postgres" -conn_str="postgres://postgres:@pgsql/xorm_test?sslmode=disable" -schema=xorm -coverprofile=coverage5-1.txt -covermode=atomic
- - go test -v -race -db="postgres" -conn_str="postgres://postgres:@pgsql/xorm_test?sslmode=disable" -schema=xorm -cache=true -coverprofile=coverage5-2.txt -covermode=atomic
- - gocovmerge coverage1-1.txt coverage1-2.txt coverage2-1.txt coverage2-2.txt coverage2.1-1.txt coverage2.1-2.txt coverage3-1.txt coverage3-2.txt coverage4-1.txt coverage4-2.txt coverage5-1.txt coverage5-2.txt > coverage.txt
- when:
- event: [ push, pull_request ]
-
- #coverage:
- # image: robertstettner/drone-codecov
- # secrets: [ codecov_token ]
- # files:
- # - coverage.txt
- # when:
- # event: [ push, pull_request ]
- # branch: [ master ]
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/.gitignore b/vendor/github.com/go-xorm/xorm/.gitignore
deleted file mode 100644
index f1757b9..0000000
--- a/vendor/github.com/go-xorm/xorm/.gitignore
+++ /dev/null
@@ -1,33 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-*.db
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-
-*.log
-.vendor
-temp_test.go
-.vscode
-xorm.test
-*.sqlite3
-test.db.sql
-
-.idea/
diff --git a/vendor/github.com/go-xorm/xorm/CONTRIBUTING.md b/vendor/github.com/go-xorm/xorm/CONTRIBUTING.md
deleted file mode 100644
index 37f4bc5..0000000
--- a/vendor/github.com/go-xorm/xorm/CONTRIBUTING.md
+++ /dev/null
@@ -1,46 +0,0 @@
-## Contributing to xorm
-
-`xorm` has a backlog of [pull requests](https://help.github.com/articles/using-pull-requests), but contributions are still very
-much welcome. You can help with patch review, submitting bug reports,
-or adding new functionality. There is no formal style guide, but
-please conform to the style of existing code and general Go formatting
-conventions when submitting patches.
-
-* [fork a repo](https://help.github.com/articles/fork-a-repo)
-* [creating a pull request ](https://help.github.com/articles/creating-a-pull-request)
-
-### Language
-
-Since `xorm` is a world-wide open source project, please describe your issues or code changes in English as soon as possible.
-
-### Sign your codes with comments
-```
-// !! your comments
-
-e.g.,
-
-// !lunny! this is comments made by lunny
-```
-
-### Patch review
-
-Help review existing open [pull requests](https://help.github.com/articles/using-pull-requests) by commenting on the code or
-proposed functionality.
-
-### Bug reports
-
-We appreciate any bug reports, but especially ones with self-contained
-(doesn't depend on code outside of xorm), minimal (can't be simplified
-further) test cases. It's especially helpful if you can submit a pull
-request with just the failing test case(you can find some example test file like [session_get_test.go](https://github.com/go-xorm/xorm/blob/master/session_get_test.go)).
-
-If you implements a new database interface, you maybe need to add a test_.sh file.
-For example, [mysql_test.go](https://github.com/go-xorm/xorm/blob/master/test_mysql.sh)
-
-### New functionality
-
-There are a number of pending patches for new functionality, so
-additional feature patches will take a while to merge. Still, patches
-are generally reviewed based on usefulness and complexity in addition
-to time-in-queue, so if you have a knockout idea, take a shot. Feel
-free to open an issue discussion your proposed patch beforehand.
diff --git a/vendor/github.com/go-xorm/xorm/LICENSE b/vendor/github.com/go-xorm/xorm/LICENSE
deleted file mode 100644
index 84d2ae5..0000000
--- a/vendor/github.com/go-xorm/xorm/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2013 - 2015 The Xorm Authors
-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 {organization} 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
diff --git a/vendor/github.com/go-xorm/xorm/README.md b/vendor/github.com/go-xorm/xorm/README.md
deleted file mode 100644
index 2b839d5..0000000
--- a/vendor/github.com/go-xorm/xorm/README.md
+++ /dev/null
@@ -1,496 +0,0 @@
-# xorm
-
-[中文](https://github.com/go-xorm/xorm/blob/master/README_CN.md)
-
-Xorm is a simple and powerful ORM for Go.
-
-[](https://circleci.com/gh/go-xorm/xorm) [](https://codecov.io/gh/go-xorm/xorm)
-[](https://goreportcard.com/report/github.com/go-xorm/xorm)
-[](https://discord.gg/HuR2CF3)
-
-## Features
-
-* Struct <-> Table Mapping Support
-
-* Chainable APIs
-
-* Transaction Support
-
-* Both ORM and raw SQL operation Support
-
-* Sync database schema Support
-
-* Query Cache speed up
-
-* Database Reverse support, See [Xorm Tool README](https://github.com/go-xorm/cmd/blob/master/README.md)
-
-* Simple cascade loading support
-
-* Optimistic Locking support
-
-* SQL Builder support via [xorm.io/builder](https://xorm.io/builder)
-
-* Automatical Read/Write seperatelly
-
-* Postgres schema support
-
-* Context Cache support
-
-## Drivers Support
-
-Drivers for Go's sql package which currently support database/sql includes:
-
-* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
-
-* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/tree/master/godrv)
-
-* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
-
-* Tidb: [github.com/pingcap/tidb](https://github.com/pingcap/tidb)
-
-* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
-
-* MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb)
-
-* Oracle: [github.com/mattn/go-oci8](https://github.com/mattn/go-oci8) (experiment)
-
-## Installation
-
- go get github.com/go-xorm/xorm
-
-## Documents
-
-* [Manual](http://xorm.io/docs)
-
-* [GoDoc](http://godoc.org/github.com/go-xorm/xorm)
-
-## Quick Start
-
-* Create Engine
-
-```Go
-engine, err := xorm.NewEngine(driverName, dataSourceName)
-```
-
-* Define a struct and Sync2 table struct to database
-
-```Go
-type User struct {
- Id int64
- Name string
- Salt string
- Age int
- Passwd string `xorm:"varchar(200)"`
- Created time.Time `xorm:"created"`
- Updated time.Time `xorm:"updated"`
-}
-
-err := engine.Sync2(new(User))
-```
-
-* Create Engine Group
-
-```Go
-dataSourceNameSlice := []string{masterDataSourceName, slave1DataSourceName, slave2DataSourceName}
-engineGroup, err := xorm.NewEngineGroup(driverName, dataSourceNameSlice)
-```
-
-```Go
-masterEngine, err := xorm.NewEngine(driverName, masterDataSourceName)
-slave1Engine, err := xorm.NewEngine(driverName, slave1DataSourceName)
-slave2Engine, err := xorm.NewEngine(driverName, slave2DataSourceName)
-engineGroup, err := xorm.NewEngineGroup(masterEngine, []*Engine{slave1Engine, slave2Engine})
-```
-
-Then all place where `engine` you can just use `engineGroup`.
-
-* `Query` runs a SQL string, the returned results is `[]map[string][]byte`, `QueryString` returns `[]map[string]string`, `QueryInterface` returns `[]map[string]interface{}`.
-
-```Go
-results, err := engine.Query("select * from user")
-results, err := engine.Where("a = 1").Query()
-
-results, err := engine.QueryString("select * from user")
-results, err := engine.Where("a = 1").QueryString()
-
-results, err := engine.QueryInterface("select * from user")
-results, err := engine.Where("a = 1").QueryInterface()
-```
-
-* `Exec` runs a SQL string, it returns `affected` and `error`
-
-```Go
-affected, err := engine.Exec("update user set age = ? where name = ?", age, name)
-```
-
-* `Insert` one or multiple records to database
-
-```Go
-affected, err := engine.Insert(&user)
-// INSERT INTO struct () values ()
-
-affected, err := engine.Insert(&user1, &user2)
-// INSERT INTO struct1 () values ()
-// INSERT INTO struct2 () values ()
-
-affected, err := engine.Insert(&users)
-// INSERT INTO struct () values (),(),()
-
-affected, err := engine.Insert(&user1, &users)
-// INSERT INTO struct1 () values ()
-// INSERT INTO struct2 () values (),(),()
-```
-
-* `Get` query one record from database
-
-```Go
-has, err := engine.Get(&user)
-// SELECT * FROM user LIMIT 1
-
-has, err := engine.Where("name = ?", name).Desc("id").Get(&user)
-// SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1
-
-var name string
-has, err := engine.Table(&user).Where("id = ?", id).Cols("name").Get(&name)
-// SELECT name FROM user WHERE id = ?
-
-var id int64
-has, err := engine.Table(&user).Where("name = ?", name).Cols("id").Get(&id)
-has, err := engine.SQL("select id from user").Get(&id)
-// SELECT id FROM user WHERE name = ?
-
-var valuesMap = make(map[string]string)
-has, err := engine.Table(&user).Where("id = ?", id).Get(&valuesMap)
-// SELECT * FROM user WHERE id = ?
-
-var valuesSlice = make([]interface{}, len(cols))
-has, err := engine.Table(&user).Where("id = ?", id).Cols(cols...).Get(&valuesSlice)
-// SELECT col1, col2, col3 FROM user WHERE id = ?
-```
-
-* `Exist` check if one record exist on table
-
-```Go
-has, err := testEngine.Exist(new(RecordExist))
-// SELECT * FROM record_exist LIMIT 1
-
-has, err = testEngine.Exist(&RecordExist{
- Name: "test1",
- })
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-
-has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{})
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-
-has, err = testEngine.SQL("select * from record_exist where name = ?", "test1").Exist()
-// select * from record_exist where name = ?
-
-has, err = testEngine.Table("record_exist").Exist()
-// SELECT * FROM record_exist LIMIT 1
-
-has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist()
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-```
-
-* `Find` query multiple records from database, also you can use join and extends
-
-```Go
-var users []User
-err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users)
-// SELECT * FROM user WHERE name = ? AND age > 10 limit 10 offset 0
-
-type Detail struct {
- Id int64
- UserId int64 `xorm:"index"`
-}
-
-type UserDetail struct {
- User `xorm:"extends"`
- Detail `xorm:"extends"`
-}
-
-var users []UserDetail
-err := engine.Table("user").Select("user.*, detail.*").
- Join("INNER", "detail", "detail.user_id = user.id").
- Where("user.name = ?", name).Limit(10, 0).
- Find(&users)
-// SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 10 offset 0
-```
-
-* `Iterate` and `Rows` query multiple records and record by record handle, there are two methods Iterate and Rows
-
-```Go
-err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
- user := bean.(*User)
- return nil
-})
-// SELECT * FROM user
-
-err := engine.BufferSize(100).Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
- user := bean.(*User)
- return nil
-})
-// SELECT * FROM user Limit 0, 100
-// SELECT * FROM user Limit 101, 100
-
-rows, err := engine.Rows(&User{Name:name})
-// SELECT * FROM user
-defer rows.Close()
-bean := new(Struct)
-for rows.Next() {
- err = rows.Scan(bean)
-}
-```
-
-* `Update` update one or more records, default will update non-empty and non-zero fields except when you use Cols, AllCols and so on.
-
-```Go
-affected, err := engine.ID(1).Update(&user)
-// UPDATE user SET ... Where id = ?
-
-affected, err := engine.Update(&user, &User{Name:name})
-// UPDATE user SET ... Where name = ?
-
-var ids = []int64{1, 2, 3}
-affected, err := engine.In("id", ids).Update(&user)
-// UPDATE user SET ... Where id IN (?, ?, ?)
-
-// force update indicated columns by Cols
-affected, err := engine.ID(1).Cols("age").Update(&User{Name:name, Age: 12})
-// UPDATE user SET age = ?, updated=? Where id = ?
-
-// force NOT update indicated columns by Omit
-affected, err := engine.ID(1).Omit("name").Update(&User{Name:name, Age: 12})
-// UPDATE user SET age = ?, updated=? Where id = ?
-
-affected, err := engine.ID(1).AllCols().Update(&user)
-// UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ?
-```
-
-* `Delete` delete one or more records, Delete MUST have condition
-
-```Go
-affected, err := engine.Where(...).Delete(&user)
-// DELETE FROM user Where ...
-
-affected, err := engine.ID(2).Delete(&user)
-// DELETE FROM user Where id = ?
-```
-
-* `Count` count records
-
-```Go
-counts, err := engine.Count(&user)
-// SELECT count(*) AS total FROM user
-```
-
-* `Sum` sum functions
-
-```Go
-agesFloat64, err := engine.Sum(&user, "age")
-// SELECT sum(age) AS total FROM user
-
-agesInt64, err := engine.SumInt(&user, "age")
-// SELECT sum(age) AS total FROM user
-
-sumFloat64Slice, err := engine.Sums(&user, "age", "score")
-// SELECT sum(age), sum(score) FROM user
-
-sumInt64Slice, err := engine.SumsInt(&user, "age", "score")
-// SELECT sum(age), sum(score) FROM user
-```
-
-* Query conditions builder
-
-```Go
-err := engine.Where(builder.NotIn("a", 1, 2).And(builder.In("b", "c", "d", "e"))).Find(&users)
-// SELECT id, name ... FROM user WHERE a NOT IN (?, ?) AND b IN (?, ?, ?)
-```
-
-* Multiple operations in one go routine, no transation here but resue session memory
-
-```Go
-session := engine.NewSession()
-defer session.Close()
-
-user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
-if _, err := session.Insert(&user1); err != nil {
- return err
-}
-
-user2 := Userinfo{Username: "yyy"}
-if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return err
-}
-
-if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return err
-}
-
-return nil
-```
-
-* Transation should on one go routine. There is transaction and resue session memory
-
-```Go
-session := engine.NewSession()
-defer session.Close()
-
-// add Begin() before any action
-if err := session.Begin(); err != nil {
- // if returned then will rollback automatically
- return err
-}
-
-user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
-if _, err := session.Insert(&user1); err != nil {
- return err
-}
-
-user2 := Userinfo{Username: "yyy"}
-if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return err
-}
-
-if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return err
-}
-
-// add Commit() after all actions
-return session.Commit()
-```
-
-* Or you can use `Transaction` to replace above codes.
-
-```Go
-res, err := engine.Transaction(func(session *xorm.Session) (interface{}, error) {
- user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
- if _, err := session.Insert(&user1); err != nil {
- return nil, err
- }
-
- user2 := Userinfo{Username: "yyy"}
- if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return nil, err
- }
-
- if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return nil, err
- }
- return nil, nil
-})
-```
-
-* Context Cache, if enabled, current query result will be cached on session and be used by next same statement on the same session.
-
-```Go
- sess := engine.NewSession()
- defer sess.Close()
-
- var context = xorm.NewMemoryContextCache()
-
- var c2 ContextGetStruct
- has, err := sess.ID(1).ContextCache(context).Get(&c2)
- assert.NoError(t, err)
- assert.True(t, has)
- assert.EqualValues(t, 1, c2.Id)
- assert.EqualValues(t, "1", c2.Name)
- sql, args := sess.LastSQL()
- assert.True(t, len(sql) > 0)
- assert.True(t, len(args) > 0)
-
- var c3 ContextGetStruct
- has, err = sess.ID(1).ContextCache(context).Get(&c3)
- assert.NoError(t, err)
- assert.True(t, has)
- assert.EqualValues(t, 1, c3.Id)
- assert.EqualValues(t, "1", c3.Name)
- sql, args = sess.LastSQL()
- assert.True(t, len(sql) == 0)
- assert.True(t, len(args) == 0)
-```
-
-## Contributing
-
-If you want to pull request, please see [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md). And we also provide [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm) to discuss.
-
-## Credits
-
-### Contributors
-
-This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
-
-
-### Backers
-
-Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/xorm#backer)]
-
-
-
-### Sponsors
-
-Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/xorm#sponsor)]
-
-## Changelog
-
-* **v0.7.0**
- * Some bugs fixed
-
-* **v0.6.6**
- * Some bugs fixed
-
-* **v0.6.5**
- * Postgres schema support
- * vgo support
- * Add FindAndCount
- * Database special params support via NewEngineWithParams
- * Some bugs fixed
-
-* **v0.6.4**
- * Automatical Read/Write seperatelly
- * Query/QueryString/QueryInterface and action with Where/And
- * Get support non-struct variables
- * BufferSize on Iterate
- * fix some other bugs.
-
-[More changes ...](https://github.com/go-xorm/manual-en-US/tree/master/chapter-16)
-
-## Cases
-
-* [studygolang](http://studygolang.com/) - [github.com/studygolang/studygolang](https://github.com/studygolang/studygolang)
-
-* [Gitea](http://gitea.io) - [github.com/go-gitea/gitea](http://github.com/go-gitea/gitea)
-
-* [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs)
-
-* [grafana](https://grafana.com/) - [github.com/grafana/grafana](http://github.com/grafana/grafana)
-
-* [github.com/m3ng9i/qreader](https://github.com/m3ng9i/qreader)
-
-* [Wego](http://github.com/go-tango/wego)
-
-* [Docker.cn](https://docker.cn/)
-
-* [Xorm Adapter](https://github.com/casbin/xorm-adapter) for [Casbin](https://github.com/casbin/casbin) - [github.com/casbin/xorm-adapter](https://github.com/casbin/xorm-adapter)
-
-* [Gorevel](http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel)
-
-* [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
-
-* [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild)
-
-* [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress)
-
-* [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily)
-
-* [YouGam](http://www.yougam.com/)
-
-* [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS)
-
-* [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/)
-
-* [go-blog](http://wangcheng.me) - [github.com/easykoo/go-blog](https://github.com/easykoo/go-blog)
-
-## LICENSE
-
-BSD License [http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)
diff --git a/vendor/github.com/go-xorm/xorm/README_CN.md b/vendor/github.com/go-xorm/xorm/README_CN.md
deleted file mode 100644
index 0cec6ed..0000000
--- a/vendor/github.com/go-xorm/xorm/README_CN.md
+++ /dev/null
@@ -1,500 +0,0 @@
-# xorm
-
-[English](https://github.com/go-xorm/xorm/blob/master/README.md)
-
-xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。
-
-[](https://circleci.com/gh/go-xorm/xorm) [](https://codecov.io/gh/go-xorm/xorm)
-[](https://goreportcard.com/report/github.com/go-xorm/xorm)
-[](https://discord.gg/HuR2CF3)
-
-## 特性
-
-* 支持Struct和数据库表之间的灵活映射,并支持自动同步
-
-* 事务支持
-
-* 同时支持原始SQL语句和ORM操作的混合执行
-
-* 使用连写来简化调用
-
-* 支持使用Id, In, Where, Limit, Join, Having, Table, Sql, Cols等函数和结构体等方式作为条件
-
-* 支持级联加载Struct
-
-* Schema支持(仅Postgres)
-
-* 支持缓存
-
-* 支持根据数据库自动生成xorm的结构体
-
-* 支持记录版本(即乐观锁)
-
-* 内置SQL Builder支持
-
-* 上下文缓存支持
-
-## 驱动支持
-
-目前支持的Go数据库驱动和对应的数据库如下:
-
-* Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
-
-* MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv)
-
-* Postgres: [github.com/lib/pq](https://github.com/lib/pq)
-
-* Tidb: [github.com/pingcap/tidb](https://github.com/pingcap/tidb)
-
-* SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3)
-
-* MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb)
-
-* MsSql: [github.com/lunny/godbc](https://github.com/lunny/godbc)
-
-* Oracle: [github.com/mattn/go-oci8](https://github.com/mattn/go-oci8) (试验性支持)
-
-## 安装
-
- go get github.com/go-xorm/xorm
-
-## 文档
-
-* [操作指南](http://xorm.io/docs)
-
-* [GoWalker代码文档](http://gowalker.org/github.com/go-xorm/xorm)
-
-* [Godoc代码文档](http://godoc.org/github.com/go-xorm/xorm)
-
-# 快速开始
-
-* 第一步创建引擎,driverName, dataSourceName和database/sql接口相同
-
-```Go
-engine, err := xorm.NewEngine(driverName, dataSourceName)
-```
-
-* 定义一个和表同步的结构体,并且自动同步结构体到数据库
-
-```Go
-type User struct {
- Id int64
- Name string
- Salt string
- Age int
- Passwd string `xorm:"varchar(200)"`
- Created time.Time `xorm:"created"`
- Updated time.Time `xorm:"updated"`
-}
-
-err := engine.Sync2(new(User))
-```
-
-* 创建Engine组
-
-```Go
-dataSourceNameSlice := []string{masterDataSourceName, slave1DataSourceName, slave2DataSourceName}
-engineGroup, err := xorm.NewEngineGroup(driverName, dataSourceNameSlice)
-```
-
-```Go
-masterEngine, err := xorm.NewEngine(driverName, masterDataSourceName)
-slave1Engine, err := xorm.NewEngine(driverName, slave1DataSourceName)
-slave2Engine, err := xorm.NewEngine(driverName, slave2DataSourceName)
-engineGroup, err := xorm.NewEngineGroup(masterEngine, []*Engine{slave1Engine, slave2Engine})
-```
-
-所有使用 `engine` 都可以简单的用 `engineGroup` 来替换。
-
-* `Query` 最原始的也支持SQL语句查询,返回的结果类型为 []map[string][]byte。`QueryString` 返回 []map[string]string, `QueryInterface` 返回 `[]map[string]interface{}`.
-
-```Go
-results, err := engine.Query("select * from user")
-results, err := engine.Where("a = 1").Query()
-
-results, err := engine.QueryString("select * from user")
-results, err := engine.Where("a = 1").QueryString()
-
-results, err := engine.QueryInterface("select * from user")
-results, err := engine.Where("a = 1").QueryInterface()
-```
-
-* `Exec` 执行一个SQL语句
-
-```Go
-affected, err := engine.Exec("update user set age = ? where name = ?", age, name)
-```
-
-* `Insert` 插入一条或者多条记录
-
-```Go
-affected, err := engine.Insert(&user)
-// INSERT INTO struct () values ()
-
-affected, err := engine.Insert(&user1, &user2)
-// INSERT INTO struct1 () values ()
-// INSERT INTO struct2 () values ()
-
-affected, err := engine.Insert(&users)
-// INSERT INTO struct () values (),(),()
-
-affected, err := engine.Insert(&user1, &users)
-// INSERT INTO struct1 () values ()
-// INSERT INTO struct2 () values (),(),()
-```
-
-* `Get` 查询单条记录
-
-```Go
-has, err := engine.Get(&user)
-// SELECT * FROM user LIMIT 1
-
-has, err := engine.Where("name = ?", name).Desc("id").Get(&user)
-// SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1
-
-var name string
-has, err := engine.Table(&user).Where("id = ?", id).Cols("name").Get(&name)
-// SELECT name FROM user WHERE id = ?
-
-var id int64
-has, err := engine.Table(&user).Where("name = ?", name).Cols("id").Get(&id)
-has, err := engine.SQL("select id from user").Get(&id)
-// SELECT id FROM user WHERE name = ?
-
-var valuesMap = make(map[string]string)
-has, err := engine.Table(&user).Where("id = ?", id).Get(&valuesMap)
-// SELECT * FROM user WHERE id = ?
-
-var valuesSlice = make([]interface{}, len(cols))
-has, err := engine.Table(&user).Where("id = ?", id).Cols(cols...).Get(&valuesSlice)
-// SELECT col1, col2, col3 FROM user WHERE id = ?
-```
-
-* `Exist` 检测记录是否存在
-
-```Go
-has, err := testEngine.Exist(new(RecordExist))
-// SELECT * FROM record_exist LIMIT 1
-
-has, err = testEngine.Exist(&RecordExist{
- Name: "test1",
- })
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-
-has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{})
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-
-has, err = testEngine.SQL("select * from record_exist where name = ?", "test1").Exist()
-// select * from record_exist where name = ?
-
-has, err = testEngine.Table("record_exist").Exist()
-// SELECT * FROM record_exist LIMIT 1
-
-has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist()
-// SELECT * FROM record_exist WHERE name = ? LIMIT 1
-```
-
-* `Find` 查询多条记录,当然可以使用Join和extends来组合使用
-
-```Go
-var users []User
-err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users)
-// SELECT * FROM user WHERE name = ? AND age > 10 limit 10 offset 0
-
-type Detail struct {
- Id int64
- UserId int64 `xorm:"index"`
-}
-
-type UserDetail struct {
- User `xorm:"extends"`
- Detail `xorm:"extends"`
-}
-
-var users []UserDetail
-err := engine.Table("user").Select("user.*, detail.*")
- Join("INNER", "detail", "detail.user_id = user.id").
- Where("user.name = ?", name).Limit(10, 0).
- Find(&users)
-// SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 10 offset 0
-```
-
-* `Iterate` 和 `Rows` 根据条件遍历数据库,可以有两种方式: Iterate and Rows
-
-```Go
-err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
- user := bean.(*User)
- return nil
-})
-// SELECT * FROM user
-
-err := engine.BufferSize(100).Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
- user := bean.(*User)
- return nil
-})
-// SELECT * FROM user Limit 0, 100
-// SELECT * FROM user Limit 101, 100
-
-rows, err := engine.Rows(&User{Name:name})
-// SELECT * FROM user
-defer rows.Close()
-bean := new(Struct)
-for rows.Next() {
- err = rows.Scan(bean)
-}
-```
-
-* `Update` 更新数据,除非使用Cols,AllCols函数指明,默认只更新非空和非0的字段
-
-```Go
-affected, err := engine.ID(1).Update(&user)
-// UPDATE user SET ... Where id = ?
-
-affected, err := engine.Update(&user, &User{Name:name})
-// UPDATE user SET ... Where name = ?
-
-var ids = []int64{1, 2, 3}
-affected, err := engine.In(ids).Update(&user)
-// UPDATE user SET ... Where id IN (?, ?, ?)
-
-// force update indicated columns by Cols
-affected, err := engine.ID(1).Cols("age").Update(&User{Name:name, Age: 12})
-// UPDATE user SET age = ?, updated=? Where id = ?
-
-// force NOT update indicated columns by Omit
-affected, err := engine.ID(1).Omit("name").Update(&User{Name:name, Age: 12})
-// UPDATE user SET age = ?, updated=? Where id = ?
-
-affected, err := engine.ID(1).AllCols().Update(&user)
-// UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ?
-```
-
-* `Delete` 删除记录,需要注意,删除必须至少有一个条件,否则会报错。要清空数据库可以用EmptyTable
-
-```Go
-affected, err := engine.Where(...).Delete(&user)
-// DELETE FROM user Where ...
-
-affected, err := engine.ID(2).Delete(&user)
-// DELETE FROM user Where id = ?
-```
-
-* `Count` 获取记录条数
-
-```Go
-counts, err := engine.Count(&user)
-// SELECT count(*) AS total FROM user
-```
-
-* `Sum` 求和函数
-
-```Go
-agesFloat64, err := engine.Sum(&user, "age")
-// SELECT sum(age) AS total FROM user
-
-agesInt64, err := engine.SumInt(&user, "age")
-// SELECT sum(age) AS total FROM user
-
-sumFloat64Slice, err := engine.Sums(&user, "age", "score")
-// SELECT sum(age), sum(score) FROM user
-
-sumInt64Slice, err := engine.SumsInt(&user, "age", "score")
-// SELECT sum(age), sum(score) FROM user
-```
-
-* 条件编辑器
-
-```Go
-err := engine.Where(builder.NotIn("a", 1, 2).And(builder.In("b", "c", "d", "e"))).Find(&users)
-// SELECT id, name ... FROM user WHERE a NOT IN (?, ?) AND b IN (?, ?, ?)
-```
-
-* 在一个Go程中多次操作数据库,但没有事务
-
-```Go
-session := engine.NewSession()
-defer session.Close()
-
-user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
-if _, err := session.Insert(&user1); err != nil {
- return err
-}
-
-user2 := Userinfo{Username: "yyy"}
-if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return err
-}
-
-if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return err
-}
-
-return nil
-```
-
-* 在一个Go程中有事务
-
-```Go
-session := engine.NewSession()
-defer session.Close()
-
-// add Begin() before any action
-if err := session.Begin(); err != nil {
- // if returned then will rollback automatically
- return err
-}
-
-user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
-if _, err := session.Insert(&user1); err != nil {
- return err
-}
-
-user2 := Userinfo{Username: "yyy"}
-if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return err
-}
-
-if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return err
-}
-
-// add Commit() after all actions
-return session.Commit()
-```
-
-* 事务的简写方法
-
-```Go
-res, err := engine.Transaction(func(session *xorm.Session) (interface{}, error) {
- user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
- if _, err := session.Insert(&user1); err != nil {
- return nil, err
- }
-
- user2 := Userinfo{Username: "yyy"}
- if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
- return nil, err
- }
-
- if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
- return nil, err
- }
- return nil, nil
-})
-```
-
-* 上下文缓存,如果启用,那么针对单个对象的查询将会被缓存到系统中,可以被下一个查询使用。
-
-```Go
- sess := engine.NewSession()
- defer sess.Close()
-
- var context = xorm.NewMemoryContextCache()
-
- var c2 ContextGetStruct
- has, err := sess.ID(1).ContextCache(context).Get(&c2)
- assert.NoError(t, err)
- assert.True(t, has)
- assert.EqualValues(t, 1, c2.Id)
- assert.EqualValues(t, "1", c2.Name)
- sql, args := sess.LastSQL()
- assert.True(t, len(sql) > 0)
- assert.True(t, len(args) > 0)
-
- var c3 ContextGetStruct
- has, err = sess.ID(1).ContextCache(context).Get(&c3)
- assert.NoError(t, err)
- assert.True(t, has)
- assert.EqualValues(t, 1, c3.Id)
- assert.EqualValues(t, "1", c3.Name)
- sql, args = sess.LastSQL()
- assert.True(t, len(sql) == 0)
- assert.True(t, len(args) == 0)
-```
-
-## 贡献
-
-如果您也想为Xorm贡献您的力量,请查看 [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md)。您也可以加入QQ群 技术帮助和讨论。
-群一:280360085 (已满)
-群二:795010183
-
-## Credits
-
-### Contributors
-
-感谢所有的贡献者. [[Contribute](CONTRIBUTING.md)].
-
-
-### Backers
-
-感谢我们所有的 backers! 🙏 [[成为 backer](https://opencollective.com/xorm#backer)]
-
-
-
-### Sponsors
-
-成为 sponsor 来支持 xorm。您的 logo 将会被显示并被链接到您的网站。 [[成为 sponsor](https://opencollective.com/xorm#sponsor)]
-
-# 案例
-
-* [Go语言中文网](http://studygolang.com/) - [github.com/studygolang/studygolang](https://github.com/studygolang/studygolang)
-
-* [Gitea](http://gitea.io) - [github.com/go-gitea/gitea](http://github.com/go-gitea/gitea)
-
-* [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs)
-
-* [grafana](https://grafana.com/) - [github.com/grafana/grafana](http://github.com/grafana/grafana)
-
-* [github.com/m3ng9i/qreader](https://github.com/m3ng9i/qreader)
-
-* [Wego](http://github.com/go-tango/wego)
-
-* [Docker.cn](https://docker.cn/)
-
-* [Xorm Adapter](https://github.com/casbin/xorm-adapter) for [Casbin](https://github.com/casbin/casbin) - [github.com/casbin/xorm-adapter](https://github.com/casbin/xorm-adapter)
-
-* [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker)
-
-* [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild)
-
-* [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress)
-
-* [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily)
-
-* [YouGam](http://www.yougam.com/)
-
-* [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS)
-
-* [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/)
-
-* [go-blog](http://wangcheng.me) - [github.com/easykoo/go-blog](https://github.com/easykoo/go-blog)
-
-
-## 更新日志
-
-* **v0.7.0**
- * 修正部分Bug
-
-* **v0.6.6**
- * 修正部分Bug
-
-* **v0.6.5**
- * 通过 engine.SetSchema 来支持 schema,当前仅支持Postgres
- * vgo 支持
- * 新增 `FindAndCount` 函数
- * 通过 `NewEngineWithParams` 支持数据库特别参数
- * 修正部分Bug
-
-* **v0.6.4**
- * 自动读写分离支持
- * Query/QueryString/QueryInterface 支持与 Where/And 合用
- * `Get` 支持获取非结构体变量
- * `Iterate` 支持 `BufferSize`
- * 修正部分Bug
-
-[更多更新日志...](https://github.com/go-xorm/manual-zh-CN/tree/master/chapter-16)
-
-## LICENSE
-
-BSD License
-[http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/)
diff --git a/vendor/github.com/go-xorm/xorm/cache_lru.go b/vendor/github.com/go-xorm/xorm/cache_lru.go
deleted file mode 100644
index ab948bd..0000000
--- a/vendor/github.com/go-xorm/xorm/cache_lru.go
+++ /dev/null
@@ -1,284 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "container/list"
- "fmt"
- "sync"
- "time"
-
- "xorm.io/core"
-)
-
-// LRUCacher implments cache object facilities
-type LRUCacher struct {
- idList *list.List
- sqlList *list.List
- idIndex map[string]map[string]*list.Element
- sqlIndex map[string]map[string]*list.Element
- store core.CacheStore
- mutex sync.Mutex
- MaxElementSize int
- Expired time.Duration
- GcInterval time.Duration
-}
-
-// NewLRUCacher creates a cacher
-func NewLRUCacher(store core.CacheStore, maxElementSize int) *LRUCacher {
- return NewLRUCacher2(store, 3600*time.Second, maxElementSize)
-}
-
-// NewLRUCacher2 creates a cache include different params
-func NewLRUCacher2(store core.CacheStore, expired time.Duration, maxElementSize int) *LRUCacher {
- cacher := &LRUCacher{store: store, idList: list.New(),
- sqlList: list.New(), Expired: expired,
- GcInterval: core.CacheGcInterval, MaxElementSize: maxElementSize,
- sqlIndex: make(map[string]map[string]*list.Element),
- idIndex: make(map[string]map[string]*list.Element),
- }
- cacher.RunGC()
- return cacher
-}
-
-// RunGC run once every m.GcInterval
-func (m *LRUCacher) RunGC() {
- time.AfterFunc(m.GcInterval, func() {
- m.RunGC()
- m.GC()
- })
-}
-
-// GC check ids lit and sql list to remove all element expired
-func (m *LRUCacher) GC() {
- m.mutex.Lock()
- defer m.mutex.Unlock()
- var removedNum int
- for e := m.idList.Front(); e != nil; {
- if removedNum <= core.CacheGcMaxRemoved &&
- time.Now().Sub(e.Value.(*idNode).lastVisit) > m.Expired {
- removedNum++
- next := e.Next()
- node := e.Value.(*idNode)
- m.delBean(node.tbName, node.id)
- e = next
- } else {
- break
- }
- }
-
- removedNum = 0
- for e := m.sqlList.Front(); e != nil; {
- if removedNum <= core.CacheGcMaxRemoved &&
- time.Now().Sub(e.Value.(*sqlNode).lastVisit) > m.Expired {
- removedNum++
- next := e.Next()
- node := e.Value.(*sqlNode)
- m.delIds(node.tbName, node.sql)
- e = next
- } else {
- break
- }
- }
-}
-
-// GetIds returns all bean's ids according to sql and parameter from cache
-func (m *LRUCacher) GetIds(tableName, sql string) interface{} {
- m.mutex.Lock()
- defer m.mutex.Unlock()
- if _, ok := m.sqlIndex[tableName]; !ok {
- m.sqlIndex[tableName] = make(map[string]*list.Element)
- }
- if v, err := m.store.Get(sql); err == nil {
- if el, ok := m.sqlIndex[tableName][sql]; !ok {
- el = m.sqlList.PushBack(newSQLNode(tableName, sql))
- m.sqlIndex[tableName][sql] = el
- } else {
- lastTime := el.Value.(*sqlNode).lastVisit
- // if expired, remove the node and return nil
- if time.Now().Sub(lastTime) > m.Expired {
- m.delIds(tableName, sql)
- return nil
- }
- m.sqlList.MoveToBack(el)
- el.Value.(*sqlNode).lastVisit = time.Now()
- }
- return v
- }
-
- m.delIds(tableName, sql)
- return nil
-}
-
-// GetBean returns bean according tableName and id from cache
-func (m *LRUCacher) GetBean(tableName string, id string) interface{} {
- m.mutex.Lock()
- defer m.mutex.Unlock()
- if _, ok := m.idIndex[tableName]; !ok {
- m.idIndex[tableName] = make(map[string]*list.Element)
- }
- tid := genID(tableName, id)
- if v, err := m.store.Get(tid); err == nil {
- if el, ok := m.idIndex[tableName][id]; ok {
- lastTime := el.Value.(*idNode).lastVisit
- // if expired, remove the node and return nil
- if time.Now().Sub(lastTime) > m.Expired {
- m.delBean(tableName, id)
- return nil
- }
- m.idList.MoveToBack(el)
- el.Value.(*idNode).lastVisit = time.Now()
- } else {
- el = m.idList.PushBack(newIDNode(tableName, id))
- m.idIndex[tableName][id] = el
- }
- return v
- }
-
- // store bean is not exist, then remove memory's index
- m.delBean(tableName, id)
- return nil
-}
-
-// clearIds clears all sql-ids mapping on table tableName from cache
-func (m *LRUCacher) clearIds(tableName string) {
- if tis, ok := m.sqlIndex[tableName]; ok {
- for sql, v := range tis {
- m.sqlList.Remove(v)
- m.store.Del(sql)
- }
- }
- m.sqlIndex[tableName] = make(map[string]*list.Element)
-}
-
-// ClearIds clears all sql-ids mapping on table tableName from cache
-func (m *LRUCacher) ClearIds(tableName string) {
- m.mutex.Lock()
- m.clearIds(tableName)
- m.mutex.Unlock()
-}
-
-func (m *LRUCacher) clearBeans(tableName string) {
- if tis, ok := m.idIndex[tableName]; ok {
- for id, v := range tis {
- m.idList.Remove(v)
- tid := genID(tableName, id)
- m.store.Del(tid)
- }
- }
- m.idIndex[tableName] = make(map[string]*list.Element)
-}
-
-// ClearBeans clears all beans in some table
-func (m *LRUCacher) ClearBeans(tableName string) {
- m.mutex.Lock()
- m.clearBeans(tableName)
- m.mutex.Unlock()
-}
-
-// PutIds pus ids into table
-func (m *LRUCacher) PutIds(tableName, sql string, ids interface{}) {
- m.mutex.Lock()
- if _, ok := m.sqlIndex[tableName]; !ok {
- m.sqlIndex[tableName] = make(map[string]*list.Element)
- }
- if el, ok := m.sqlIndex[tableName][sql]; !ok {
- el = m.sqlList.PushBack(newSQLNode(tableName, sql))
- m.sqlIndex[tableName][sql] = el
- } else {
- el.Value.(*sqlNode).lastVisit = time.Now()
- }
- m.store.Put(sql, ids)
- if m.sqlList.Len() > m.MaxElementSize {
- e := m.sqlList.Front()
- node := e.Value.(*sqlNode)
- m.delIds(node.tbName, node.sql)
- }
- m.mutex.Unlock()
-}
-
-// PutBean puts beans into table
-func (m *LRUCacher) PutBean(tableName string, id string, obj interface{}) {
- m.mutex.Lock()
- var el *list.Element
- var ok bool
-
- if el, ok = m.idIndex[tableName][id]; !ok {
- el = m.idList.PushBack(newIDNode(tableName, id))
- m.idIndex[tableName][id] = el
- } else {
- el.Value.(*idNode).lastVisit = time.Now()
- }
-
- m.store.Put(genID(tableName, id), obj)
- if m.idList.Len() > m.MaxElementSize {
- e := m.idList.Front()
- node := e.Value.(*idNode)
- m.delBean(node.tbName, node.id)
- }
- m.mutex.Unlock()
-}
-
-func (m *LRUCacher) delIds(tableName, sql string) {
- if _, ok := m.sqlIndex[tableName]; ok {
- if el, ok := m.sqlIndex[tableName][sql]; ok {
- delete(m.sqlIndex[tableName], sql)
- m.sqlList.Remove(el)
- }
- }
- m.store.Del(sql)
-}
-
-// DelIds deletes ids
-func (m *LRUCacher) DelIds(tableName, sql string) {
- m.mutex.Lock()
- m.delIds(tableName, sql)
- m.mutex.Unlock()
-}
-
-func (m *LRUCacher) delBean(tableName string, id string) {
- tid := genID(tableName, id)
- if el, ok := m.idIndex[tableName][id]; ok {
- delete(m.idIndex[tableName], id)
- m.idList.Remove(el)
- m.clearIds(tableName)
- }
- m.store.Del(tid)
-}
-
-// DelBean deletes beans in some table
-func (m *LRUCacher) DelBean(tableName string, id string) {
- m.mutex.Lock()
- m.delBean(tableName, id)
- m.mutex.Unlock()
-}
-
-type idNode struct {
- tbName string
- id string
- lastVisit time.Time
-}
-
-type sqlNode struct {
- tbName string
- sql string
- lastVisit time.Time
-}
-
-func genSQLKey(sql string, args interface{}) string {
- return fmt.Sprintf("%v-%v", sql, args)
-}
-
-func genID(prefix string, id string) string {
- return fmt.Sprintf("%v-%v", prefix, id)
-}
-
-func newIDNode(tbName string, id string) *idNode {
- return &idNode{tbName, id, time.Now()}
-}
-
-func newSQLNode(tbName, sql string) *sqlNode {
- return &sqlNode{tbName, sql, time.Now()}
-}
diff --git a/vendor/github.com/go-xorm/xorm/cache_memory_store.go b/vendor/github.com/go-xorm/xorm/cache_memory_store.go
deleted file mode 100644
index 0c483f4..0000000
--- a/vendor/github.com/go-xorm/xorm/cache_memory_store.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "sync"
-
- "xorm.io/core"
-)
-
-var _ core.CacheStore = NewMemoryStore()
-
-// MemoryStore represents in-memory store
-type MemoryStore struct {
- store map[interface{}]interface{}
- mutex sync.RWMutex
-}
-
-// NewMemoryStore creates a new store in memory
-func NewMemoryStore() *MemoryStore {
- return &MemoryStore{store: make(map[interface{}]interface{})}
-}
-
-// Put puts object into store
-func (s *MemoryStore) Put(key string, value interface{}) error {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- s.store[key] = value
- return nil
-}
-
-// Get gets object from store
-func (s *MemoryStore) Get(key string) (interface{}, error) {
- s.mutex.RLock()
- defer s.mutex.RUnlock()
- if v, ok := s.store[key]; ok {
- return v, nil
- }
-
- return nil, ErrNotExist
-}
-
-// Del deletes object
-func (s *MemoryStore) Del(key string) error {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- delete(s.store, key)
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/context_cache.go b/vendor/github.com/go-xorm/xorm/context_cache.go
deleted file mode 100644
index 1bc2288..0000000
--- a/vendor/github.com/go-xorm/xorm/context_cache.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2018 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-// ContextCache is the interface that operates the cache data.
-type ContextCache interface {
- // Put puts value into cache with key.
- Put(key string, val interface{})
- // Get gets cached value by given key.
- Get(key string) interface{}
-}
-
-type memoryContextCache map[string]interface{}
-
-// NewMemoryContextCache return memoryContextCache
-func NewMemoryContextCache() memoryContextCache {
- return make(map[string]interface{})
-}
-
-// Put puts value into cache with key.
-func (m memoryContextCache) Put(key string, val interface{}) {
- m[key] = val
-}
-
-// Get gets cached value by given key.
-func (m memoryContextCache) Get(key string) interface{} {
- return m[key]
-}
diff --git a/vendor/github.com/go-xorm/xorm/convert.go b/vendor/github.com/go-xorm/xorm/convert.go
deleted file mode 100644
index 2316ca0..0000000
--- a/vendor/github.com/go-xorm/xorm/convert.go
+++ /dev/null
@@ -1,348 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql/driver"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "time"
-)
-
-var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error
-
-func strconvErr(err error) error {
- if ne, ok := err.(*strconv.NumError); ok {
- return ne.Err
- }
- return err
-}
-
-func cloneBytes(b []byte) []byte {
- if b == nil {
- return nil
- } else {
- c := make([]byte, len(b))
- copy(c, b)
- return c
- }
-}
-
-func asString(src interface{}) string {
- switch v := src.(type) {
- case string:
- return v
- case []byte:
- return string(v)
- }
- rv := reflect.ValueOf(src)
- switch rv.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return strconv.FormatInt(rv.Int(), 10)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return strconv.FormatUint(rv.Uint(), 10)
- case reflect.Float64:
- return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
- case reflect.Float32:
- return strconv.FormatFloat(rv.Float(), 'g', -1, 32)
- case reflect.Bool:
- return strconv.FormatBool(rv.Bool())
- }
- return fmt.Sprintf("%v", src)
-}
-
-func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
- switch rv.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return strconv.AppendInt(buf, rv.Int(), 10), true
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return strconv.AppendUint(buf, rv.Uint(), 10), true
- case reflect.Float32:
- return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
- case reflect.Float64:
- return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
- case reflect.Bool:
- return strconv.AppendBool(buf, rv.Bool()), true
- case reflect.String:
- s := rv.String()
- return append(buf, s...), true
- }
- return
-}
-
-// convertAssign copies to dest the value in src, converting it if possible.
-// An error is returned if the copy would result in loss of information.
-// dest should be a pointer type.
-func convertAssign(dest, src interface{}) error {
- // Common cases, without reflect.
- switch s := src.(type) {
- case string:
- switch d := dest.(type) {
- case *string:
- if d == nil {
- return errNilPtr
- }
- *d = s
- return nil
- case *[]byte:
- if d == nil {
- return errNilPtr
- }
- *d = []byte(s)
- return nil
- }
- case []byte:
- switch d := dest.(type) {
- case *string:
- if d == nil {
- return errNilPtr
- }
- *d = string(s)
- return nil
- case *interface{}:
- if d == nil {
- return errNilPtr
- }
- *d = cloneBytes(s)
- return nil
- case *[]byte:
- if d == nil {
- return errNilPtr
- }
- *d = cloneBytes(s)
- return nil
- }
-
- case time.Time:
- switch d := dest.(type) {
- case *string:
- *d = s.Format(time.RFC3339Nano)
- return nil
- case *[]byte:
- if d == nil {
- return errNilPtr
- }
- *d = []byte(s.Format(time.RFC3339Nano))
- return nil
- }
- case nil:
- switch d := dest.(type) {
- case *interface{}:
- if d == nil {
- return errNilPtr
- }
- *d = nil
- return nil
- case *[]byte:
- if d == nil {
- return errNilPtr
- }
- *d = nil
- return nil
- }
- }
-
- var sv reflect.Value
-
- switch d := dest.(type) {
- case *string:
- sv = reflect.ValueOf(src)
- switch sv.Kind() {
- case reflect.Bool,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
- reflect.Float32, reflect.Float64:
- *d = asString(src)
- return nil
- }
- case *[]byte:
- sv = reflect.ValueOf(src)
- if b, ok := asBytes(nil, sv); ok {
- *d = b
- return nil
- }
- case *bool:
- bv, err := driver.Bool.ConvertValue(src)
- if err == nil {
- *d = bv.(bool)
- }
- return err
- case *interface{}:
- *d = src
- return nil
- }
-
- dpv := reflect.ValueOf(dest)
- if dpv.Kind() != reflect.Ptr {
- return errors.New("destination not a pointer")
- }
- if dpv.IsNil() {
- return errNilPtr
- }
-
- if !sv.IsValid() {
- sv = reflect.ValueOf(src)
- }
-
- dv := reflect.Indirect(dpv)
- if sv.IsValid() && sv.Type().AssignableTo(dv.Type()) {
- switch b := src.(type) {
- case []byte:
- dv.Set(reflect.ValueOf(cloneBytes(b)))
- default:
- dv.Set(sv)
- }
- return nil
- }
-
- if dv.Kind() == sv.Kind() && sv.Type().ConvertibleTo(dv.Type()) {
- dv.Set(sv.Convert(dv.Type()))
- return nil
- }
-
- switch dv.Kind() {
- case reflect.Ptr:
- if src == nil {
- dv.Set(reflect.Zero(dv.Type()))
- return nil
- }
-
- dv.Set(reflect.New(dv.Type().Elem()))
- return convertAssign(dv.Interface(), src)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- s := asString(src)
- i64, err := strconv.ParseInt(s, 10, dv.Type().Bits())
- if err != nil {
- err = strconvErr(err)
- return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
- }
- dv.SetInt(i64)
- return nil
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- s := asString(src)
- u64, err := strconv.ParseUint(s, 10, dv.Type().Bits())
- if err != nil {
- err = strconvErr(err)
- return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
- }
- dv.SetUint(u64)
- return nil
- case reflect.Float32, reflect.Float64:
- s := asString(src)
- f64, err := strconv.ParseFloat(s, dv.Type().Bits())
- if err != nil {
- err = strconvErr(err)
- return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err)
- }
- dv.SetFloat(f64)
- return nil
- case reflect.String:
- dv.SetString(asString(src))
- return nil
- }
-
- return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, dest)
-}
-
-func asKind(vv reflect.Value, tp reflect.Type) (interface{}, error) {
- switch tp.Kind() {
- case reflect.Int64:
- return vv.Int(), nil
- case reflect.Int:
- return int(vv.Int()), nil
- case reflect.Int32:
- return int32(vv.Int()), nil
- case reflect.Int16:
- return int16(vv.Int()), nil
- case reflect.Int8:
- return int8(vv.Int()), nil
- case reflect.Uint64:
- return vv.Uint(), nil
- case reflect.Uint:
- return uint(vv.Uint()), nil
- case reflect.Uint32:
- return uint32(vv.Uint()), nil
- case reflect.Uint16:
- return uint16(vv.Uint()), nil
- case reflect.Uint8:
- return uint8(vv.Uint()), nil
- case reflect.String:
- return vv.String(), nil
- case reflect.Slice:
- if tp.Elem().Kind() == reflect.Uint8 {
- v, err := strconv.ParseInt(string(vv.Interface().([]byte)), 10, 64)
- if err != nil {
- return nil, err
- }
- return v, nil
- }
-
- }
- return nil, fmt.Errorf("unsupported primary key type: %v, %v", tp, vv)
-}
-
-func convertFloat(v interface{}) (float64, error) {
- switch v.(type) {
- case float32:
- return float64(v.(float32)), nil
- case float64:
- return v.(float64), nil
- case string:
- i, err := strconv.ParseFloat(v.(string), 64)
- if err != nil {
- return 0, err
- }
- return i, nil
- case []byte:
- i, err := strconv.ParseFloat(string(v.([]byte)), 64)
- if err != nil {
- return 0, err
- }
- return i, nil
- }
- return 0, fmt.Errorf("unsupported type: %v", v)
-}
-
-func convertInt(v interface{}) (int64, error) {
- switch v.(type) {
- case int:
- return int64(v.(int)), nil
- case int8:
- return int64(v.(int8)), nil
- case int16:
- return int64(v.(int16)), nil
- case int32:
- return int64(v.(int32)), nil
- case int64:
- return v.(int64), nil
- case []byte:
- i, err := strconv.ParseInt(string(v.([]byte)), 10, 64)
- if err != nil {
- return 0, err
- }
- return i, nil
- case string:
- i, err := strconv.ParseInt(v.(string), 10, 64)
- if err != nil {
- return 0, err
- }
- return i, nil
- }
- return 0, fmt.Errorf("unsupported type: %v", v)
-}
-
-func asBool(bs []byte) (bool, error) {
- if len(bs) == 0 {
- return false, nil
- }
- if bs[0] == 0x00 {
- return false, nil
- } else if bs[0] == 0x01 {
- return true, nil
- }
- return strconv.ParseBool(string(bs))
-}
diff --git a/vendor/github.com/go-xorm/xorm/dialect_mssql.go b/vendor/github.com/go-xorm/xorm/dialect_mssql.go
deleted file mode 100644
index 3330212..0000000
--- a/vendor/github.com/go-xorm/xorm/dialect_mssql.go
+++ /dev/null
@@ -1,572 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "net/url"
- "strconv"
- "strings"
-
- "xorm.io/core"
-)
-
-var (
- mssqlReservedWords = map[string]bool{
- "ADD": true,
- "EXTERNAL": true,
- "PROCEDURE": true,
- "ALL": true,
- "FETCH": true,
- "PUBLIC": true,
- "ALTER": true,
- "FILE": true,
- "RAISERROR": true,
- "AND": true,
- "FILLFACTOR": true,
- "READ": true,
- "ANY": true,
- "FOR": true,
- "READTEXT": true,
- "AS": true,
- "FOREIGN": true,
- "RECONFIGURE": true,
- "ASC": true,
- "FREETEXT": true,
- "REFERENCES": true,
- "AUTHORIZATION": true,
- "FREETEXTTABLE": true,
- "REPLICATION": true,
- "BACKUP": true,
- "FROM": true,
- "RESTORE": true,
- "BEGIN": true,
- "FULL": true,
- "RESTRICT": true,
- "BETWEEN": true,
- "FUNCTION": true,
- "RETURN": true,
- "BREAK": true,
- "GOTO": true,
- "REVERT": true,
- "BROWSE": true,
- "GRANT": true,
- "REVOKE": true,
- "BULK": true,
- "GROUP": true,
- "RIGHT": true,
- "BY": true,
- "HAVING": true,
- "ROLLBACK": true,
- "CASCADE": true,
- "HOLDLOCK": true,
- "ROWCOUNT": true,
- "CASE": true,
- "IDENTITY": true,
- "ROWGUIDCOL": true,
- "CHECK": true,
- "IDENTITY_INSERT": true,
- "RULE": true,
- "CHECKPOINT": true,
- "IDENTITYCOL": true,
- "SAVE": true,
- "CLOSE": true,
- "IF": true,
- "SCHEMA": true,
- "CLUSTERED": true,
- "IN": true,
- "SECURITYAUDIT": true,
- "COALESCE": true,
- "INDEX": true,
- "SELECT": true,
- "COLLATE": true,
- "INNER": true,
- "SEMANTICKEYPHRASETABLE": true,
- "COLUMN": true,
- "INSERT": true,
- "SEMANTICSIMILARITYDETAILSTABLE": true,
- "COMMIT": true,
- "INTERSECT": true,
- "SEMANTICSIMILARITYTABLE": true,
- "COMPUTE": true,
- "INTO": true,
- "SESSION_USER": true,
- "CONSTRAINT": true,
- "IS": true,
- "SET": true,
- "CONTAINS": true,
- "JOIN": true,
- "SETUSER": true,
- "CONTAINSTABLE": true,
- "KEY": true,
- "SHUTDOWN": true,
- "CONTINUE": true,
- "KILL": true,
- "SOME": true,
- "CONVERT": true,
- "LEFT": true,
- "STATISTICS": true,
- "CREATE": true,
- "LIKE": true,
- "SYSTEM_USER": true,
- "CROSS": true,
- "LINENO": true,
- "TABLE": true,
- "CURRENT": true,
- "LOAD": true,
- "TABLESAMPLE": true,
- "CURRENT_DATE": true,
- "MERGE": true,
- "TEXTSIZE": true,
- "CURRENT_TIME": true,
- "NATIONAL": true,
- "THEN": true,
- "CURRENT_TIMESTAMP": true,
- "NOCHECK": true,
- "TO": true,
- "CURRENT_USER": true,
- "NONCLUSTERED": true,
- "TOP": true,
- "CURSOR": true,
- "NOT": true,
- "TRAN": true,
- "DATABASE": true,
- "NULL": true,
- "TRANSACTION": true,
- "DBCC": true,
- "NULLIF": true,
- "TRIGGER": true,
- "DEALLOCATE": true,
- "OF": true,
- "TRUNCATE": true,
- "DECLARE": true,
- "OFF": true,
- "TRY_CONVERT": true,
- "DEFAULT": true,
- "OFFSETS": true,
- "TSEQUAL": true,
- "DELETE": true,
- "ON": true,
- "UNION": true,
- "DENY": true,
- "OPEN": true,
- "UNIQUE": true,
- "DESC": true,
- "OPENDATASOURCE": true,
- "UNPIVOT": true,
- "DISK": true,
- "OPENQUERY": true,
- "UPDATE": true,
- "DISTINCT": true,
- "OPENROWSET": true,
- "UPDATETEXT": true,
- "DISTRIBUTED": true,
- "OPENXML": true,
- "USE": true,
- "DOUBLE": true,
- "OPTION": true,
- "USER": true,
- "DROP": true,
- "OR": true,
- "VALUES": true,
- "DUMP": true,
- "ORDER": true,
- "VARYING": true,
- "ELSE": true,
- "OUTER": true,
- "VIEW": true,
- "END": true,
- "OVER": true,
- "WAITFOR": true,
- "ERRLVL": true,
- "PERCENT": true,
- "WHEN": true,
- "ESCAPE": true,
- "PIVOT": true,
- "WHERE": true,
- "EXCEPT": true,
- "PLAN": true,
- "WHILE": true,
- "EXEC": true,
- "PRECISION": true,
- "WITH": true,
- "EXECUTE": true,
- "PRIMARY": true,
- "WITHIN": true,
- "EXISTS": true,
- "PRINT": true,
- "WRITETEXT": true,
- "EXIT": true,
- "PROC": true,
- }
-)
-
-type mssql struct {
- core.Base
-}
-
-func (db *mssql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
- return db.Base.Init(d, db, uri, drivername, dataSourceName)
-}
-
-func (db *mssql) SqlType(c *core.Column) string {
- var res string
- switch t := c.SQLType.Name; t {
- case core.Bool:
- res = core.Bit
- if strings.EqualFold(c.Default, "true") {
- c.Default = "1"
- } else if strings.EqualFold(c.Default, "false") {
- c.Default = "0"
- }
- case core.Serial:
- c.IsAutoIncrement = true
- c.IsPrimaryKey = true
- c.Nullable = false
- res = core.Int
- case core.BigSerial:
- c.IsAutoIncrement = true
- c.IsPrimaryKey = true
- c.Nullable = false
- res = core.BigInt
- case core.Bytea, core.Blob, core.Binary, core.TinyBlob, core.MediumBlob, core.LongBlob:
- res = core.VarBinary
- if c.Length == 0 {
- c.Length = 50
- }
- case core.TimeStamp:
- res = core.DateTime
- case core.TimeStampz:
- res = "DATETIMEOFFSET"
- c.Length = 7
- case core.MediumInt:
- res = core.Int
- case core.Text, core.MediumText, core.TinyText, core.LongText, core.Json:
- res = core.Varchar + "(MAX)"
- case core.Double:
- res = core.Real
- case core.Uuid:
- res = core.Varchar
- c.Length = 40
- case core.TinyInt:
- res = core.TinyInt
- c.Length = 0
- default:
- res = t
- }
-
- if res == core.Int {
- return core.Int
- }
-
- hasLen1 := (c.Length > 0)
- hasLen2 := (c.Length2 > 0)
-
- if hasLen2 {
- res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
- } else if hasLen1 {
- res += "(" + strconv.Itoa(c.Length) + ")"
- }
- return res
-}
-
-func (db *mssql) SupportInsertMany() bool {
- return true
-}
-
-func (db *mssql) IsReserved(name string) bool {
- _, ok := mssqlReservedWords[name]
- return ok
-}
-
-func (db *mssql) Quote(name string) string {
- return "\"" + name + "\""
-}
-
-func (db *mssql) QuoteStr() string {
- return "\""
-}
-
-func (db *mssql) SupportEngine() bool {
- return false
-}
-
-func (db *mssql) AutoIncrStr() string {
- return "IDENTITY"
-}
-
-func (db *mssql) DropTableSql(tableName string) string {
- return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+
- "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+
- "DROP TABLE \"%s\"", tableName, tableName)
-}
-
-func (db *mssql) SupportCharset() bool {
- return false
-}
-
-func (db *mssql) IndexOnTable() bool {
- return true
-}
-
-func (db *mssql) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
- args := []interface{}{idxName}
- sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?"
- return sql, args
-}
-
-/*func (db *mssql) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
- args := []interface{}{tableName, colName}
- sql := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
- return sql, args
-}*/
-
-func (db *mssql) IsColumnExist(tableName, colName string) (bool, error) {
- query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?`
-
- return db.HasRecords(query, tableName, colName)
-}
-
-func (db *mssql) TableCheckSql(tableName string) (string, []interface{}) {
- args := []interface{}{}
- sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1"
- return sql, args
-}
-
-func (db *mssql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
- args := []interface{}{}
- s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale,a.is_nullable as nullable,
- replace(replace(isnull(c.text,''),'(',''),')','') as vdefault,
- ISNULL(i.is_primary_key, 0)
- from sys.columns a
- left join sys.types b on a.user_type_id=b.user_type_id
- left join sys.syscomments c on a.default_object_id=c.id
- LEFT OUTER JOIN
- sys.index_columns ic ON ic.object_id = a.object_id AND ic.column_id = a.column_id
- LEFT OUTER JOIN
- sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
- where a.object_id=object_id('` + tableName + `')`
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, nil, err
- }
- defer rows.Close()
-
- cols := make(map[string]*core.Column)
- colSeq := make([]string, 0)
- for rows.Next() {
- var name, ctype, vdefault string
- var maxLen, precision, scale int
- var nullable, isPK bool
- err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale, &nullable, &vdefault, &isPK)
- if err != nil {
- return nil, nil, err
- }
-
- col := new(core.Column)
- col.Indexes = make(map[string]int)
- col.Name = strings.Trim(name, "` ")
- col.Nullable = nullable
- col.Default = vdefault
- col.IsPrimaryKey = isPK
- ct := strings.ToUpper(ctype)
- if ct == "DECIMAL" {
- col.Length = precision
- col.Length2 = scale
- } else {
- col.Length = maxLen
- }
- switch ct {
- case "DATETIMEOFFSET":
- col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
- case "NVARCHAR":
- col.SQLType = core.SQLType{Name: core.NVarchar, DefaultLength: 0, DefaultLength2: 0}
- case "IMAGE":
- col.SQLType = core.SQLType{Name: core.VarBinary, DefaultLength: 0, DefaultLength2: 0}
- default:
- if _, ok := core.SqlTypes[ct]; ok {
- col.SQLType = core.SQLType{Name: ct, DefaultLength: 0, DefaultLength2: 0}
- } else {
- return nil, nil, fmt.Errorf("Unknown colType %v for %v - %v", ct, tableName, col.Name)
- }
- }
-
- if col.SQLType.IsText() || col.SQLType.IsTime() {
- if col.Default != "" {
- col.Default = "'" + col.Default + "'"
- } else {
- if col.DefaultIsEmpty {
- col.Default = "''"
- }
- }
- }
- cols[col.Name] = col
- colSeq = append(colSeq, col.Name)
- }
- return colSeq, cols, nil
-}
-
-func (db *mssql) GetTables() ([]*core.Table, error) {
- args := []interface{}{}
- s := `select name from sysobjects where xtype ='U'`
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- tables := make([]*core.Table, 0)
- for rows.Next() {
- table := core.NewEmptyTable()
- var name string
- err = rows.Scan(&name)
- if err != nil {
- return nil, err
- }
- table.Name = strings.Trim(name, "` ")
- tables = append(tables, table)
- }
- return tables, nil
-}
-
-func (db *mssql) GetIndexes(tableName string) (map[string]*core.Index, error) {
- args := []interface{}{tableName}
- s := `SELECT
-IXS.NAME AS [INDEX_NAME],
-C.NAME AS [COLUMN_NAME],
-IXS.is_unique AS [IS_UNIQUE]
-FROM SYS.INDEXES IXS
-INNER JOIN SYS.INDEX_COLUMNS IXCS
-ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID
-INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID
-AND IXCS.COLUMN_ID=C.COLUMN_ID
-WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =?
-`
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- indexes := make(map[string]*core.Index, 0)
- for rows.Next() {
- var indexType int
- var indexName, colName, isUnique string
-
- err = rows.Scan(&indexName, &colName, &isUnique)
- if err != nil {
- return nil, err
- }
-
- i, err := strconv.ParseBool(isUnique)
- if err != nil {
- return nil, err
- }
-
- if i {
- indexType = core.UniqueType
- } else {
- indexType = core.IndexType
- }
-
- colName = strings.Trim(colName, "` ")
- var isRegular bool
- if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
- indexName = indexName[5+len(tableName):]
- isRegular = true
- }
-
- var index *core.Index
- var ok bool
- if index, ok = indexes[indexName]; !ok {
- index = new(core.Index)
- index.Type = indexType
- index.Name = indexName
- index.IsRegular = isRegular
- indexes[indexName] = index
- }
- index.AddColumn(colName)
- }
- return indexes, nil
-}
-
-func (db *mssql) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string {
- var sql string
- if tableName == "" {
- tableName = table.Name
- }
-
- sql = "IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '" + tableName + "' ) CREATE TABLE "
-
- sql += db.QuoteStr() + tableName + db.QuoteStr() + " ("
-
- pkList := table.PrimaryKeys
-
- for _, colName := range table.ColumnsSeq() {
- col := table.GetColumn(colName)
- if col.IsPrimaryKey && len(pkList) == 1 {
- sql += col.String(db)
- } else {
- sql += col.StringNoPk(db)
- }
- sql = strings.TrimSpace(sql)
- sql += ", "
- }
-
- if len(pkList) > 1 {
- sql += "PRIMARY KEY ( "
- sql += strings.Join(pkList, ",")
- sql += " ), "
- }
-
- sql = sql[:len(sql)-2] + ")"
- sql += ";"
- return sql
-}
-
-func (db *mssql) ForUpdateSql(query string) string {
- return query
-}
-
-func (db *mssql) Filters() []core.Filter {
- return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}}
-}
-
-type odbcDriver struct {
-}
-
-func (p *odbcDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- var dbName string
-
- if strings.HasPrefix(dataSourceName, "sqlserver://") {
- u, err := url.Parse(dataSourceName)
- if err != nil {
- return nil, err
- }
- dbName = u.Query().Get("database")
- } else {
- kv := strings.Split(dataSourceName, ";")
- for _, c := range kv {
- vv := strings.Split(strings.TrimSpace(c), "=")
- if len(vv) == 2 {
- switch strings.ToLower(vv[0]) {
- case "database":
- dbName = vv[1]
- }
- }
- }
- }
- if dbName == "" {
- return nil, errors.New("no db name provided")
- }
- return &core.Uri{DbName: dbName, DbType: core.MSSQL}, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/dialect_mysql.go b/vendor/github.com/go-xorm/xorm/dialect_mysql.go
deleted file mode 100644
index 2628042..0000000
--- a/vendor/github.com/go-xorm/xorm/dialect_mysql.go
+++ /dev/null
@@ -1,662 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "crypto/tls"
- "errors"
- "fmt"
- "regexp"
- "strconv"
- "strings"
- "time"
-
- "xorm.io/core"
-)
-
-var (
- mysqlReservedWords = map[string]bool{
- "ADD": true,
- "ALL": true,
- "ALTER": true,
- "ANALYZE": true,
- "AND": true,
- "AS": true,
- "ASC": true,
- "ASENSITIVE": true,
- "BEFORE": true,
- "BETWEEN": true,
- "BIGINT": true,
- "BINARY": true,
- "BLOB": true,
- "BOTH": true,
- "BY": true,
- "CALL": true,
- "CASCADE": true,
- "CASE": true,
- "CHANGE": true,
- "CHAR": true,
- "CHARACTER": true,
- "CHECK": true,
- "COLLATE": true,
- "COLUMN": true,
- "CONDITION": true,
- "CONNECTION": true,
- "CONSTRAINT": true,
- "CONTINUE": true,
- "CONVERT": true,
- "CREATE": true,
- "CROSS": true,
- "CURRENT_DATE": true,
- "CURRENT_TIME": true,
- "CURRENT_TIMESTAMP": true,
- "CURRENT_USER": true,
- "CURSOR": true,
- "DATABASE": true,
- "DATABASES": true,
- "DAY_HOUR": true,
- "DAY_MICROSECOND": true,
- "DAY_MINUTE": true,
- "DAY_SECOND": true,
- "DEC": true,
- "DECIMAL": true,
- "DECLARE": true,
- "DEFAULT": true,
- "DELAYED": true,
- "DELETE": true,
- "DESC": true,
- "DESCRIBE": true,
- "DETERMINISTIC": true,
- "DISTINCT": true,
- "DISTINCTROW": true,
- "DIV": true,
- "DOUBLE": true,
- "DROP": true,
- "DUAL": true,
- "EACH": true,
- "ELSE": true,
- "ELSEIF": true,
- "ENCLOSED": true,
- "ESCAPED": true,
- "EXISTS": true,
- "EXIT": true,
- "EXPLAIN": true,
- "FALSE": true,
- "FETCH": true,
- "FLOAT": true,
- "FLOAT4": true,
- "FLOAT8": true,
- "FOR": true,
- "FORCE": true,
- "FOREIGN": true,
- "FROM": true,
- "FULLTEXT": true,
- "GOTO": true,
- "GRANT": true,
- "GROUP": true,
- "HAVING": true,
- "HIGH_PRIORITY": true,
- "HOUR_MICROSECOND": true,
- "HOUR_MINUTE": true,
- "HOUR_SECOND": true,
- "IF": true,
- "IGNORE": true,
- "IN": true, "INDEX": true,
- "INFILE": true, "INNER": true, "INOUT": true,
- "INSENSITIVE": true, "INSERT": true, "INT": true,
- "INT1": true, "INT2": true, "INT3": true,
- "INT4": true, "INT8": true, "INTEGER": true,
- "INTERVAL": true, "INTO": true, "IS": true,
- "ITERATE": true, "JOIN": true, "KEY": true,
- "KEYS": true, "KILL": true, "LABEL": true,
- "LEADING": true, "LEAVE": true, "LEFT": true,
- "LIKE": true, "LIMIT": true, "LINEAR": true,
- "LINES": true, "LOAD": true, "LOCALTIME": true,
- "LOCALTIMESTAMP": true, "LOCK": true, "LONG": true,
- "LONGBLOB": true, "LONGTEXT": true, "LOOP": true,
- "LOW_PRIORITY": true, "MATCH": true, "MEDIUMBLOB": true,
- "MEDIUMINT": true, "MEDIUMTEXT": true, "MIDDLEINT": true,
- "MINUTE_MICROSECOND": true, "MINUTE_SECOND": true, "MOD": true,
- "MODIFIES": true, "NATURAL": true, "NOT": true,
- "NO_WRITE_TO_BINLOG": true, "NULL": true, "NUMERIC": true,
- "ON OPTIMIZE": true, "OPTION": true,
- "OPTIONALLY": true, "OR": true, "ORDER": true,
- "OUT": true, "OUTER": true, "OUTFILE": true,
- "PRECISION": true, "PRIMARY": true, "PROCEDURE": true,
- "PURGE": true, "RAID0": true, "RANGE": true,
- "READ": true, "READS": true, "REAL": true,
- "REFERENCES": true, "REGEXP": true, "RELEASE": true,
- "RENAME": true, "REPEAT": true, "REPLACE": true,
- "REQUIRE": true, "RESTRICT": true, "RETURN": true,
- "REVOKE": true, "RIGHT": true, "RLIKE": true,
- "SCHEMA": true, "SCHEMAS": true, "SECOND_MICROSECOND": true,
- "SELECT": true, "SENSITIVE": true, "SEPARATOR": true,
- "SET": true, "SHOW": true, "SMALLINT": true,
- "SPATIAL": true, "SPECIFIC": true, "SQL": true,
- "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true,
- "SQL_BIG_RESULT": true, "SQL_CALC_FOUND_ROWS": true, "SQL_SMALL_RESULT": true,
- "SSL": true, "STARTING": true, "STRAIGHT_JOIN": true,
- "TABLE": true, "TERMINATED": true, "THEN": true,
- "TINYBLOB": true, "TINYINT": true, "TINYTEXT": true,
- "TO": true, "TRAILING": true, "TRIGGER": true,
- "TRUE": true, "UNDO": true, "UNION": true,
- "UNIQUE": true, "UNLOCK": true, "UNSIGNED": true,
- "UPDATE": true, "USAGE": true, "USE": true,
- "USING": true, "UTC_DATE": true, "UTC_TIME": true,
- "UTC_TIMESTAMP": true, "VALUES": true, "VARBINARY": true,
- "VARCHAR": true,
- "VARCHARACTER": true,
- "VARYING": true,
- "WHEN": true,
- "WHERE": true,
- "WHILE": true,
- "WITH": true,
- "WRITE": true,
- "X509": true,
- "XOR": true,
- "YEAR_MONTH": true,
- "ZEROFILL": true,
- }
-)
-
-type mysql struct {
- core.Base
- net string
- addr string
- params map[string]string
- loc *time.Location
- timeout time.Duration
- tls *tls.Config
- allowAllFiles bool
- allowOldPasswords bool
- clientFoundRows bool
- rowFormat string
-}
-
-func (db *mysql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
- return db.Base.Init(d, db, uri, drivername, dataSourceName)
-}
-
-func (db *mysql) SetParams(params map[string]string) {
- rowFormat, ok := params["rowFormat"]
- if ok {
- var t = strings.ToUpper(rowFormat)
- switch t {
- case "COMPACT":
- fallthrough
- case "REDUNDANT":
- fallthrough
- case "DYNAMIC":
- fallthrough
- case "COMPRESSED":
- db.rowFormat = t
- break
- default:
- break
- }
- }
-}
-
-func (db *mysql) SqlType(c *core.Column) string {
- var res string
- switch t := c.SQLType.Name; t {
- case core.Bool:
- res = core.TinyInt
- c.Length = 1
- case core.Serial:
- c.IsAutoIncrement = true
- c.IsPrimaryKey = true
- c.Nullable = false
- res = core.Int
- case core.BigSerial:
- c.IsAutoIncrement = true
- c.IsPrimaryKey = true
- c.Nullable = false
- res = core.BigInt
- case core.Bytea:
- res = core.Blob
- case core.TimeStampz:
- res = core.Char
- c.Length = 64
- case core.Enum: //mysql enum
- res = core.Enum
- res += "("
- opts := ""
- for v := range c.EnumOptions {
- opts += fmt.Sprintf(",'%v'", v)
- }
- res += strings.TrimLeft(opts, ",")
- res += ")"
- case core.Set: //mysql set
- res = core.Set
- res += "("
- opts := ""
- for v := range c.SetOptions {
- opts += fmt.Sprintf(",'%v'", v)
- }
- res += strings.TrimLeft(opts, ",")
- res += ")"
- case core.NVarchar:
- res = core.Varchar
- case core.Uuid:
- res = core.Varchar
- c.Length = 40
- case core.Json:
- res = core.Text
- default:
- res = t
- }
-
- hasLen1 := (c.Length > 0)
- hasLen2 := (c.Length2 > 0)
-
- if res == core.BigInt && !hasLen1 && !hasLen2 {
- c.Length = 20
- hasLen1 = true
- }
-
- if hasLen2 {
- res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
- } else if hasLen1 {
- res += "(" + strconv.Itoa(c.Length) + ")"
- }
- return res
-}
-
-func (db *mysql) SupportInsertMany() bool {
- return true
-}
-
-func (db *mysql) IsReserved(name string) bool {
- _, ok := mysqlReservedWords[name]
- return ok
-}
-
-func (db *mysql) Quote(name string) string {
- return "`" + name + "`"
-}
-
-func (db *mysql) QuoteStr() string {
- return "`"
-}
-
-func (db *mysql) SupportEngine() bool {
- return true
-}
-
-func (db *mysql) AutoIncrStr() string {
- return "AUTO_INCREMENT"
-}
-
-func (db *mysql) SupportCharset() bool {
- return true
-}
-
-func (db *mysql) IndexOnTable() bool {
- return true
-}
-
-func (db *mysql) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
- args := []interface{}{db.DbName, tableName, idxName}
- sql := "SELECT `INDEX_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS`"
- sql += " WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `INDEX_NAME`=?"
- return sql, args
-}
-
-/*func (db *mysql) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
- args := []interface{}{db.DbName, tableName, colName}
- sql := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?"
- return sql, args
-}*/
-
-func (db *mysql) TableCheckSql(tableName string) (string, []interface{}) {
- args := []interface{}{db.DbName, tableName}
- sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?"
- return sql, args
-}
-
-func (db *mysql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
- args := []interface{}{db.DbName, tableName}
- s := "SELECT `COLUMN_NAME`, `IS_NULLABLE`, `COLUMN_DEFAULT`, `COLUMN_TYPE`," +
- " `COLUMN_KEY`, `EXTRA`,`COLUMN_COMMENT` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, nil, err
- }
- defer rows.Close()
-
- cols := make(map[string]*core.Column)
- colSeq := make([]string, 0)
- for rows.Next() {
- col := new(core.Column)
- col.Indexes = make(map[string]int)
-
- var columnName, isNullable, colType, colKey, extra, comment string
- var colDefault *string
- err = rows.Scan(&columnName, &isNullable, &colDefault, &colType, &colKey, &extra, &comment)
- if err != nil {
- return nil, nil, err
- }
- col.Name = strings.Trim(columnName, "` ")
- col.Comment = comment
- if "YES" == isNullable {
- col.Nullable = true
- }
-
- if colDefault != nil {
- col.Default = *colDefault
- if col.Default == "" {
- col.DefaultIsEmpty = true
- }
- }
-
- cts := strings.Split(colType, "(")
- colName := cts[0]
- colType = strings.ToUpper(colName)
- var len1, len2 int
- if len(cts) == 2 {
- idx := strings.Index(cts[1], ")")
- if colType == core.Enum && cts[1][0] == '\'' { //enum
- options := strings.Split(cts[1][0:idx], ",")
- col.EnumOptions = make(map[string]int)
- for k, v := range options {
- v = strings.TrimSpace(v)
- v = strings.Trim(v, "'")
- col.EnumOptions[v] = k
- }
- } else if colType == core.Set && cts[1][0] == '\'' {
- options := strings.Split(cts[1][0:idx], ",")
- col.SetOptions = make(map[string]int)
- for k, v := range options {
- v = strings.TrimSpace(v)
- v = strings.Trim(v, "'")
- col.SetOptions[v] = k
- }
- } else {
- lens := strings.Split(cts[1][0:idx], ",")
- len1, err = strconv.Atoi(strings.TrimSpace(lens[0]))
- if err != nil {
- return nil, nil, err
- }
- if len(lens) == 2 {
- len2, err = strconv.Atoi(lens[1])
- if err != nil {
- return nil, nil, err
- }
- }
- }
- }
- if colType == "FLOAT UNSIGNED" {
- colType = "FLOAT"
- }
- if colType == "DOUBLE UNSIGNED" {
- colType = "DOUBLE"
- }
- col.Length = len1
- col.Length2 = len2
- if _, ok := core.SqlTypes[colType]; ok {
- col.SQLType = core.SQLType{Name: colType, DefaultLength: len1, DefaultLength2: len2}
- } else {
- return nil, nil, fmt.Errorf("Unknown colType %v", colType)
- }
-
- if colKey == "PRI" {
- col.IsPrimaryKey = true
- }
- if colKey == "UNI" {
- //col.is
- }
-
- if extra == "auto_increment" {
- col.IsAutoIncrement = true
- }
-
- if col.SQLType.IsText() || col.SQLType.IsTime() {
- if col.Default != "" {
- col.Default = "'" + col.Default + "'"
- } else {
- if col.DefaultIsEmpty {
- col.Default = "''"
- }
- }
- }
- cols[col.Name] = col
- colSeq = append(colSeq, col.Name)
- }
- return colSeq, cols, nil
-}
-
-func (db *mysql) GetTables() ([]*core.Table, error) {
- args := []interface{}{db.DbName}
- s := "SELECT `TABLE_NAME`, `ENGINE`, `TABLE_ROWS`, `AUTO_INCREMENT`, `TABLE_COMMENT` from " +
- "`INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? AND (`ENGINE`='MyISAM' OR `ENGINE` = 'InnoDB' OR `ENGINE` = 'TokuDB')"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- tables := make([]*core.Table, 0)
- for rows.Next() {
- table := core.NewEmptyTable()
- var name, engine, tableRows, comment string
- var autoIncr *string
- err = rows.Scan(&name, &engine, &tableRows, &autoIncr, &comment)
- if err != nil {
- return nil, err
- }
-
- table.Name = name
- table.Comment = comment
- table.StoreEngine = engine
- tables = append(tables, table)
- }
- return tables, nil
-}
-
-func (db *mysql) GetIndexes(tableName string) (map[string]*core.Index, error) {
- args := []interface{}{db.DbName, tableName}
- s := "SELECT `INDEX_NAME`, `NON_UNIQUE`, `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- indexes := make(map[string]*core.Index, 0)
- for rows.Next() {
- var indexType int
- var indexName, colName, nonUnique string
- err = rows.Scan(&indexName, &nonUnique, &colName)
- if err != nil {
- return nil, err
- }
-
- if indexName == "PRIMARY" {
- continue
- }
-
- if "YES" == nonUnique || nonUnique == "1" {
- indexType = core.IndexType
- } else {
- indexType = core.UniqueType
- }
-
- colName = strings.Trim(colName, "` ")
- var isRegular bool
- if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
- indexName = indexName[5+len(tableName):]
- isRegular = true
- }
-
- var index *core.Index
- var ok bool
- if index, ok = indexes[indexName]; !ok {
- index = new(core.Index)
- index.IsRegular = isRegular
- index.Type = indexType
- index.Name = indexName
- indexes[indexName] = index
- }
- index.AddColumn(colName)
- }
- return indexes, nil
-}
-
-func (db *mysql) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string {
- var sql string
- sql = "CREATE TABLE IF NOT EXISTS "
- if tableName == "" {
- tableName = table.Name
- }
-
- sql += db.Quote(tableName)
- sql += " ("
-
- if len(table.ColumnsSeq()) > 0 {
- pkList := table.PrimaryKeys
-
- for _, colName := range table.ColumnsSeq() {
- col := table.GetColumn(colName)
- if col.IsPrimaryKey && len(pkList) == 1 {
- sql += col.String(db)
- } else {
- sql += col.StringNoPk(db)
- }
- sql = strings.TrimSpace(sql)
- if len(col.Comment) > 0 {
- sql += " COMMENT '" + col.Comment + "'"
- }
- sql += ", "
- }
-
- if len(pkList) > 1 {
- sql += "PRIMARY KEY ( "
- sql += db.Quote(strings.Join(pkList, db.Quote(",")))
- sql += " ), "
- }
-
- sql = sql[:len(sql)-2]
- }
- sql += ")"
-
- if storeEngine != "" {
- sql += " ENGINE=" + storeEngine
- }
-
- if len(charset) == 0 {
- charset = db.URI().Charset
- }
- if len(charset) != 0 {
- sql += " DEFAULT CHARSET " + charset
- }
-
-
-
- if db.rowFormat != "" {
- sql += " ROW_FORMAT=" + db.rowFormat
- }
- return sql
-}
-
-func (db *mysql) Filters() []core.Filter {
- return []core.Filter{&core.IdFilter{}}
-}
-
-type mymysqlDriver struct {
-}
-
-func (p *mymysqlDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- db := &core.Uri{DbType: core.MYSQL}
-
- pd := strings.SplitN(dataSourceName, "*", 2)
- if len(pd) == 2 {
- // Parse protocol part of URI
- p := strings.SplitN(pd[0], ":", 2)
- if len(p) != 2 {
- return nil, errors.New("Wrong protocol part of URI")
- }
- db.Proto = p[0]
- options := strings.Split(p[1], ",")
- db.Raddr = options[0]
- for _, o := range options[1:] {
- kv := strings.SplitN(o, "=", 2)
- var k, v string
- if len(kv) == 2 {
- k, v = kv[0], kv[1]
- } else {
- k, v = o, "true"
- }
- switch k {
- case "laddr":
- db.Laddr = v
- case "timeout":
- to, err := time.ParseDuration(v)
- if err != nil {
- return nil, err
- }
- db.Timeout = to
- default:
- return nil, errors.New("Unknown option: " + k)
- }
- }
- // Remove protocol part
- pd = pd[1:]
- }
- // Parse database part of URI
- dup := strings.SplitN(pd[0], "/", 3)
- if len(dup) != 3 {
- return nil, errors.New("Wrong database part of URI")
- }
- db.DbName = dup[0]
- db.User = dup[1]
- db.Passwd = dup[2]
-
- return db, nil
-}
-
-type mysqlDriver struct {
-}
-
-func (p *mysqlDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- dsnPattern := regexp.MustCompile(
- `^(?:(?P.*?)(?::(?P.*))?@)?` + // [user[:password]@]
- `(?:(?P[^\(]*)(?:\((?P[^\)]*)\))?)?` + // [net[(addr)]]
- `\/(?P.*?)` + // /dbname
- `(?:\?(?P[^\?]*))?$`) // [?param1=value1¶mN=valueN]
- matches := dsnPattern.FindStringSubmatch(dataSourceName)
- //tlsConfigRegister := make(map[string]*tls.Config)
- names := dsnPattern.SubexpNames()
-
- uri := &core.Uri{DbType: core.MYSQL}
-
- for i, match := range matches {
- switch names[i] {
- case "dbname":
- uri.DbName = match
- case "params":
- if len(match) > 0 {
- kvs := strings.Split(match, "&")
- for _, kv := range kvs {
- splits := strings.Split(kv, "=")
- if len(splits) == 2 {
- switch splits[0] {
- case "charset":
- uri.Charset = splits[1]
- }
- }
- }
- }
-
- }
- }
- return uri, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/dialect_oracle.go b/vendor/github.com/go-xorm/xorm/dialect_oracle.go
deleted file mode 100644
index b66145b..0000000
--- a/vendor/github.com/go-xorm/xorm/dialect_oracle.go
+++ /dev/null
@@ -1,906 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "regexp"
- "strconv"
- "strings"
-
- "xorm.io/core"
-)
-
-var (
- oracleReservedWords = map[string]bool{
- "ACCESS": true,
- "ACCOUNT": true,
- "ACTIVATE": true,
- "ADD": true,
- "ADMIN": true,
- "ADVISE": true,
- "AFTER": true,
- "ALL": true,
- "ALL_ROWS": true,
- "ALLOCATE": true,
- "ALTER": true,
- "ANALYZE": true,
- "AND": true,
- "ANY": true,
- "ARCHIVE": true,
- "ARCHIVELOG": true,
- "ARRAY": true,
- "AS": true,
- "ASC": true,
- "AT": true,
- "AUDIT": true,
- "AUTHENTICATED": true,
- "AUTHORIZATION": true,
- "AUTOEXTEND": true,
- "AUTOMATIC": true,
- "BACKUP": true,
- "BECOME": true,
- "BEFORE": true,
- "BEGIN": true,
- "BETWEEN": true,
- "BFILE": true,
- "BITMAP": true,
- "BLOB": true,
- "BLOCK": true,
- "BODY": true,
- "BY": true,
- "CACHE": true,
- "CACHE_INSTANCES": true,
- "CANCEL": true,
- "CASCADE": true,
- "CAST": true,
- "CFILE": true,
- "CHAINED": true,
- "CHANGE": true,
- "CHAR": true,
- "CHAR_CS": true,
- "CHARACTER": true,
- "CHECK": true,
- "CHECKPOINT": true,
- "CHOOSE": true,
- "CHUNK": true,
- "CLEAR": true,
- "CLOB": true,
- "CLONE": true,
- "CLOSE": true,
- "CLOSE_CACHED_OPEN_CURSORS": true,
- "CLUSTER": true,
- "COALESCE": true,
- "COLUMN": true,
- "COLUMNS": true,
- "COMMENT": true,
- "COMMIT": true,
- "COMMITTED": true,
- "COMPATIBILITY": true,
- "COMPILE": true,
- "COMPLETE": true,
- "COMPOSITE_LIMIT": true,
- "COMPRESS": true,
- "COMPUTE": true,
- "CONNECT": true,
- "CONNECT_TIME": true,
- "CONSTRAINT": true,
- "CONSTRAINTS": true,
- "CONTENTS": true,
- "CONTINUE": true,
- "CONTROLFILE": true,
- "CONVERT": true,
- "COST": true,
- "CPU_PER_CALL": true,
- "CPU_PER_SESSION": true,
- "CREATE": true,
- "CURRENT": true,
- "CURRENT_SCHEMA": true,
- "CURREN_USER": true,
- "CURSOR": true,
- "CYCLE": true,
- "DANGLING": true,
- "DATABASE": true,
- "DATAFILE": true,
- "DATAFILES": true,
- "DATAOBJNO": true,
- "DATE": true,
- "DBA": true,
- "DBHIGH": true,
- "DBLOW": true,
- "DBMAC": true,
- "DEALLOCATE": true,
- "DEBUG": true,
- "DEC": true,
- "DECIMAL": true,
- "DECLARE": true,
- "DEFAULT": true,
- "DEFERRABLE": true,
- "DEFERRED": true,
- "DEGREE": true,
- "DELETE": true,
- "DEREF": true,
- "DESC": true,
- "DIRECTORY": true,
- "DISABLE": true,
- "DISCONNECT": true,
- "DISMOUNT": true,
- "DISTINCT": true,
- "DISTRIBUTED": true,
- "DML": true,
- "DOUBLE": true,
- "DROP": true,
- "DUMP": true,
- "EACH": true,
- "ELSE": true,
- "ENABLE": true,
- "END": true,
- "ENFORCE": true,
- "ENTRY": true,
- "ESCAPE": true,
- "EXCEPT": true,
- "EXCEPTIONS": true,
- "EXCHANGE": true,
- "EXCLUDING": true,
- "EXCLUSIVE": true,
- "EXECUTE": true,
- "EXISTS": true,
- "EXPIRE": true,
- "EXPLAIN": true,
- "EXTENT": true,
- "EXTENTS": true,
- "EXTERNALLY": true,
- "FAILED_LOGIN_ATTEMPTS": true,
- "FALSE": true,
- "FAST": true,
- "FILE": true,
- "FIRST_ROWS": true,
- "FLAGGER": true,
- "FLOAT": true,
- "FLOB": true,
- "FLUSH": true,
- "FOR": true,
- "FORCE": true,
- "FOREIGN": true,
- "FREELIST": true,
- "FREELISTS": true,
- "FROM": true,
- "FULL": true,
- "FUNCTION": true,
- "GLOBAL": true,
- "GLOBALLY": true,
- "GLOBAL_NAME": true,
- "GRANT": true,
- "GROUP": true,
- "GROUPS": true,
- "HASH": true,
- "HASHKEYS": true,
- "HAVING": true,
- "HEADER": true,
- "HEAP": true,
- "IDENTIFIED": true,
- "IDGENERATORS": true,
- "IDLE_TIME": true,
- "IF": true,
- "IMMEDIATE": true,
- "IN": true,
- "INCLUDING": true,
- "INCREMENT": true,
- "INDEX": true,
- "INDEXED": true,
- "INDEXES": true,
- "INDICATOR": true,
- "IND_PARTITION": true,
- "INITIAL": true,
- "INITIALLY": true,
- "INITRANS": true,
- "INSERT": true,
- "INSTANCE": true,
- "INSTANCES": true,
- "INSTEAD": true,
- "INT": true,
- "INTEGER": true,
- "INTERMEDIATE": true,
- "INTERSECT": true,
- "INTO": true,
- "IS": true,
- "ISOLATION": true,
- "ISOLATION_LEVEL": true,
- "KEEP": true,
- "KEY": true,
- "KILL": true,
- "LABEL": true,
- "LAYER": true,
- "LESS": true,
- "LEVEL": true,
- "LIBRARY": true,
- "LIKE": true,
- "LIMIT": true,
- "LINK": true,
- "LIST": true,
- "LOB": true,
- "LOCAL": true,
- "LOCK": true,
- "LOCKED": true,
- "LOG": true,
- "LOGFILE": true,
- "LOGGING": true,
- "LOGICAL_READS_PER_CALL": true,
- "LOGICAL_READS_PER_SESSION": true,
- "LONG": true,
- "MANAGE": true,
- "MASTER": true,
- "MAX": true,
- "MAXARCHLOGS": true,
- "MAXDATAFILES": true,
- "MAXEXTENTS": true,
- "MAXINSTANCES": true,
- "MAXLOGFILES": true,
- "MAXLOGHISTORY": true,
- "MAXLOGMEMBERS": true,
- "MAXSIZE": true,
- "MAXTRANS": true,
- "MAXVALUE": true,
- "MIN": true,
- "MEMBER": true,
- "MINIMUM": true,
- "MINEXTENTS": true,
- "MINUS": true,
- "MINVALUE": true,
- "MLSLABEL": true,
- "MLS_LABEL_FORMAT": true,
- "MODE": true,
- "MODIFY": true,
- "MOUNT": true,
- "MOVE": true,
- "MTS_DISPATCHERS": true,
- "MULTISET": true,
- "NATIONAL": true,
- "NCHAR": true,
- "NCHAR_CS": true,
- "NCLOB": true,
- "NEEDED": true,
- "NESTED": true,
- "NETWORK": true,
- "NEW": true,
- "NEXT": true,
- "NOARCHIVELOG": true,
- "NOAUDIT": true,
- "NOCACHE": true,
- "NOCOMPRESS": true,
- "NOCYCLE": true,
- "NOFORCE": true,
- "NOLOGGING": true,
- "NOMAXVALUE": true,
- "NOMINVALUE": true,
- "NONE": true,
- "NOORDER": true,
- "NOOVERRIDE": true,
- "NOPARALLEL": true,
- "NOREVERSE": true,
- "NORMAL": true,
- "NOSORT": true,
- "NOT": true,
- "NOTHING": true,
- "NOWAIT": true,
- "NULL": true,
- "NUMBER": true,
- "NUMERIC": true,
- "NVARCHAR2": true,
- "OBJECT": true,
- "OBJNO": true,
- "OBJNO_REUSE": true,
- "OF": true,
- "OFF": true,
- "OFFLINE": true,
- "OID": true,
- "OIDINDEX": true,
- "OLD": true,
- "ON": true,
- "ONLINE": true,
- "ONLY": true,
- "OPCODE": true,
- "OPEN": true,
- "OPTIMAL": true,
- "OPTIMIZER_GOAL": true,
- "OPTION": true,
- "OR": true,
- "ORDER": true,
- "ORGANIZATION": true,
- "OSLABEL": true,
- "OVERFLOW": true,
- "OWN": true,
- "PACKAGE": true,
- "PARALLEL": true,
- "PARTITION": true,
- "PASSWORD": true,
- "PASSWORD_GRACE_TIME": true,
- "PASSWORD_LIFE_TIME": true,
- "PASSWORD_LOCK_TIME": true,
- "PASSWORD_REUSE_MAX": true,
- "PASSWORD_REUSE_TIME": true,
- "PASSWORD_VERIFY_FUNCTION": true,
- "PCTFREE": true,
- "PCTINCREASE": true,
- "PCTTHRESHOLD": true,
- "PCTUSED": true,
- "PCTVERSION": true,
- "PERCENT": true,
- "PERMANENT": true,
- "PLAN": true,
- "PLSQL_DEBUG": true,
- "POST_TRANSACTION": true,
- "PRECISION": true,
- "PRESERVE": true,
- "PRIMARY": true,
- "PRIOR": true,
- "PRIVATE": true,
- "PRIVATE_SGA": true,
- "PRIVILEGE": true,
- "PRIVILEGES": true,
- "PROCEDURE": true,
- "PROFILE": true,
- "PUBLIC": true,
- "PURGE": true,
- "QUEUE": true,
- "QUOTA": true,
- "RANGE": true,
- "RAW": true,
- "RBA": true,
- "READ": true,
- "READUP": true,
- "REAL": true,
- "REBUILD": true,
- "RECOVER": true,
- "RECOVERABLE": true,
- "RECOVERY": true,
- "REF": true,
- "REFERENCES": true,
- "REFERENCING": true,
- "REFRESH": true,
- "RENAME": true,
- "REPLACE": true,
- "RESET": true,
- "RESETLOGS": true,
- "RESIZE": true,
- "RESOURCE": true,
- "RESTRICTED": true,
- "RETURN": true,
- "RETURNING": true,
- "REUSE": true,
- "REVERSE": true,
- "REVOKE": true,
- "ROLE": true,
- "ROLES": true,
- "ROLLBACK": true,
- "ROW": true,
- "ROWID": true,
- "ROWNUM": true,
- "ROWS": true,
- "RULE": true,
- "SAMPLE": true,
- "SAVEPOINT": true,
- "SB4": true,
- "SCAN_INSTANCES": true,
- "SCHEMA": true,
- "SCN": true,
- "SCOPE": true,
- "SD_ALL": true,
- "SD_INHIBIT": true,
- "SD_SHOW": true,
- "SEGMENT": true,
- "SEG_BLOCK": true,
- "SEG_FILE": true,
- "SELECT": true,
- "SEQUENCE": true,
- "SERIALIZABLE": true,
- "SESSION": true,
- "SESSION_CACHED_CURSORS": true,
- "SESSIONS_PER_USER": true,
- "SET": true,
- "SHARE": true,
- "SHARED": true,
- "SHARED_POOL": true,
- "SHRINK": true,
- "SIZE": true,
- "SKIP": true,
- "SKIP_UNUSABLE_INDEXES": true,
- "SMALLINT": true,
- "SNAPSHOT": true,
- "SOME": true,
- "SORT": true,
- "SPECIFICATION": true,
- "SPLIT": true,
- "SQL_TRACE": true,
- "STANDBY": true,
- "START": true,
- "STATEMENT_ID": true,
- "STATISTICS": true,
- "STOP": true,
- "STORAGE": true,
- "STORE": true,
- "STRUCTURE": true,
- "SUCCESSFUL": true,
- "SWITCH": true,
- "SYS_OP_ENFORCE_NOT_NULL$": true,
- "SYS_OP_NTCIMG$": true,
- "SYNONYM": true,
- "SYSDATE": true,
- "SYSDBA": true,
- "SYSOPER": true,
- "SYSTEM": true,
- "TABLE": true,
- "TABLES": true,
- "TABLESPACE": true,
- "TABLESPACE_NO": true,
- "TABNO": true,
- "TEMPORARY": true,
- "THAN": true,
- "THE": true,
- "THEN": true,
- "THREAD": true,
- "TIMESTAMP": true,
- "TIME": true,
- "TO": true,
- "TOPLEVEL": true,
- "TRACE": true,
- "TRACING": true,
- "TRANSACTION": true,
- "TRANSITIONAL": true,
- "TRIGGER": true,
- "TRIGGERS": true,
- "TRUE": true,
- "TRUNCATE": true,
- "TX": true,
- "TYPE": true,
- "UB2": true,
- "UBA": true,
- "UID": true,
- "UNARCHIVED": true,
- "UNDO": true,
- "UNION": true,
- "UNIQUE": true,
- "UNLIMITED": true,
- "UNLOCK": true,
- "UNRECOVERABLE": true,
- "UNTIL": true,
- "UNUSABLE": true,
- "UNUSED": true,
- "UPDATABLE": true,
- "UPDATE": true,
- "USAGE": true,
- "USE": true,
- "USER": true,
- "USING": true,
- "VALIDATE": true,
- "VALIDATION": true,
- "VALUE": true,
- "VALUES": true,
- "VARCHAR": true,
- "VARCHAR2": true,
- "VARYING": true,
- "VIEW": true,
- "WHEN": true,
- "WHENEVER": true,
- "WHERE": true,
- "WITH": true,
- "WITHOUT": true,
- "WORK": true,
- "WRITE": true,
- "WRITEDOWN": true,
- "WRITEUP": true,
- "XID": true,
- "YEAR": true,
- "ZONE": true,
- }
-)
-
-type oracle struct {
- core.Base
-}
-
-func (db *oracle) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
- return db.Base.Init(d, db, uri, drivername, dataSourceName)
-}
-
-func (db *oracle) SqlType(c *core.Column) string {
- var res string
- switch t := c.SQLType.Name; t {
- case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt, core.Bool, core.Serial, core.BigSerial:
- res = "NUMBER"
- case core.Binary, core.VarBinary, core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob, core.Bytea:
- return core.Blob
- case core.Time, core.DateTime, core.TimeStamp:
- res = core.TimeStamp
- case core.TimeStampz:
- res = "TIMESTAMP WITH TIME ZONE"
- case core.Float, core.Double, core.Numeric, core.Decimal:
- res = "NUMBER"
- case core.Text, core.MediumText, core.LongText, core.Json:
- res = "CLOB"
- case core.Char, core.Varchar, core.TinyText:
- res = "VARCHAR2"
- default:
- res = t
- }
-
- hasLen1 := (c.Length > 0)
- hasLen2 := (c.Length2 > 0)
-
- if hasLen2 {
- res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
- } else if hasLen1 {
- res += "(" + strconv.Itoa(c.Length) + ")"
- }
- return res
-}
-
-func (db *oracle) AutoIncrStr() string {
- return "AUTO_INCREMENT"
-}
-
-func (db *oracle) SupportInsertMany() bool {
- return true
-}
-
-func (db *oracle) IsReserved(name string) bool {
- _, ok := oracleReservedWords[name]
- return ok
-}
-
-func (db *oracle) Quote(name string) string {
- return "\"" + name + "\""
-}
-
-func (db *oracle) QuoteStr() string {
- return "\""
-}
-
-func (db *oracle) SupportEngine() bool {
- return false
-}
-
-func (db *oracle) SupportCharset() bool {
- return false
-}
-
-func (db *oracle) SupportDropIfExists() bool {
- return false
-}
-
-func (db *oracle) IndexOnTable() bool {
- return false
-}
-
-func (db *oracle) DropTableSql(tableName string) string {
- return fmt.Sprintf("DROP TABLE `%s`", tableName)
-}
-
-func (db *oracle) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string {
- var sql string
- sql = "CREATE TABLE "
- if tableName == "" {
- tableName = table.Name
- }
-
- sql += db.Quote(tableName) + " ("
-
- pkList := table.PrimaryKeys
-
- for _, colName := range table.ColumnsSeq() {
- col := table.GetColumn(colName)
- /*if col.IsPrimaryKey && len(pkList) == 1 {
- sql += col.String(b.dialect)
- } else {*/
- sql += col.StringNoPk(db)
- //}
- sql = strings.TrimSpace(sql)
- sql += ", "
- }
-
- if len(pkList) > 0 {
- sql += "PRIMARY KEY ( "
- sql += db.Quote(strings.Join(pkList, db.Quote(",")))
- sql += " ), "
- }
-
- sql = sql[:len(sql)-2] + ")"
- if db.SupportEngine() && storeEngine != "" {
- sql += " ENGINE=" + storeEngine
- }
- if db.SupportCharset() {
- if len(charset) == 0 {
- charset = db.URI().Charset
- }
- if len(charset) > 0 {
- sql += " DEFAULT CHARSET " + charset
- }
- }
- return sql
-}
-
-func (db *oracle) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
- args := []interface{}{tableName, idxName}
- return `SELECT INDEX_NAME FROM USER_INDEXES ` +
- `WHERE TABLE_NAME = :1 AND INDEX_NAME = :2`, args
-}
-
-func (db *oracle) TableCheckSql(tableName string) (string, []interface{}) {
- args := []interface{}{tableName}
- return `SELECT table_name FROM user_tables WHERE table_name = :1`, args
-}
-
-func (db *oracle) MustDropTable(tableName string) error {
- sql, args := db.TableCheckSql(tableName)
- db.LogSQL(sql, args)
-
- rows, err := db.DB().Query(sql, args...)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- if !rows.Next() {
- return nil
- }
-
- sql = "Drop Table \"" + tableName + "\""
- db.LogSQL(sql, args)
-
- _, err = db.DB().Exec(sql)
- return err
-}
-
-/*func (db *oracle) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
- args := []interface{}{strings.ToUpper(tableName), strings.ToUpper(colName)}
- return "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = ?" +
- " AND column_name = ?", args
-}*/
-
-func (db *oracle) IsColumnExist(tableName, colName string) (bool, error) {
- args := []interface{}{tableName, colName}
- query := "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = :1" +
- " AND column_name = :2"
- db.LogSQL(query, args)
-
- rows, err := db.DB().Query(query, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- if rows.Next() {
- return true, nil
- }
- return false, nil
-}
-
-func (db *oracle) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
- args := []interface{}{tableName}
- s := "SELECT column_name,data_default,data_type,data_length,data_precision,data_scale," +
- "nullable FROM USER_TAB_COLUMNS WHERE table_name = :1"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, nil, err
- }
- defer rows.Close()
-
- cols := make(map[string]*core.Column)
- colSeq := make([]string, 0)
- for rows.Next() {
- col := new(core.Column)
- col.Indexes = make(map[string]int)
-
- var colName, colDefault, nullable, dataType, dataPrecision, dataScale *string
- var dataLen int
-
- err = rows.Scan(&colName, &colDefault, &dataType, &dataLen, &dataPrecision,
- &dataScale, &nullable)
- if err != nil {
- return nil, nil, err
- }
-
- col.Name = strings.Trim(*colName, `" `)
- if colDefault != nil {
- col.Default = *colDefault
- col.DefaultIsEmpty = false
- }
-
- if *nullable == "Y" {
- col.Nullable = true
- } else {
- col.Nullable = false
- }
-
- var ignore bool
-
- var dt string
- var len1, len2 int
- dts := strings.Split(*dataType, "(")
- dt = dts[0]
- if len(dts) > 1 {
- lens := strings.Split(dts[1][:len(dts[1])-1], ",")
- if len(lens) > 1 {
- len1, _ = strconv.Atoi(lens[0])
- len2, _ = strconv.Atoi(lens[1])
- } else {
- len1, _ = strconv.Atoi(lens[0])
- }
- }
-
- switch dt {
- case "VARCHAR2":
- col.SQLType = core.SQLType{Name: core.Varchar, DefaultLength: len1, DefaultLength2: len2}
- case "NVARCHAR2":
- col.SQLType = core.SQLType{Name: core.NVarchar, DefaultLength: len1, DefaultLength2: len2}
- case "TIMESTAMP WITH TIME ZONE":
- col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
- case "NUMBER":
- col.SQLType = core.SQLType{Name: core.Double, DefaultLength: len1, DefaultLength2: len2}
- case "LONG", "LONG RAW":
- col.SQLType = core.SQLType{Name: core.Text, DefaultLength: 0, DefaultLength2: 0}
- case "RAW":
- col.SQLType = core.SQLType{Name: core.Binary, DefaultLength: 0, DefaultLength2: 0}
- case "ROWID":
- col.SQLType = core.SQLType{Name: core.Varchar, DefaultLength: 18, DefaultLength2: 0}
- case "AQ$_SUBSCRIBERS":
- ignore = true
- default:
- col.SQLType = core.SQLType{Name: strings.ToUpper(dt), DefaultLength: len1, DefaultLength2: len2}
- }
-
- if ignore {
- continue
- }
-
- if _, ok := core.SqlTypes[col.SQLType.Name]; !ok {
- return nil, nil, fmt.Errorf("Unknown colType %v %v", *dataType, col.SQLType)
- }
-
- col.Length = dataLen
-
- if col.SQLType.IsText() || col.SQLType.IsTime() {
- if !col.DefaultIsEmpty {
- col.Default = "'" + col.Default + "'"
- }
- }
- cols[col.Name] = col
- colSeq = append(colSeq, col.Name)
- }
-
- return colSeq, cols, nil
-}
-
-func (db *oracle) GetTables() ([]*core.Table, error) {
- args := []interface{}{}
- s := "SELECT table_name FROM user_tables"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- tables := make([]*core.Table, 0)
- for rows.Next() {
- table := core.NewEmptyTable()
- err = rows.Scan(&table.Name)
- if err != nil {
- return nil, err
- }
-
- tables = append(tables, table)
- }
- return tables, nil
-}
-
-func (db *oracle) GetIndexes(tableName string) (map[string]*core.Index, error) {
- args := []interface{}{tableName}
- s := "SELECT t.column_name,i.uniqueness,i.index_name FROM user_ind_columns t,user_indexes i " +
- "WHERE t.index_name = i.index_name and t.table_name = i.table_name and t.table_name =:1"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- indexes := make(map[string]*core.Index, 0)
- for rows.Next() {
- var indexType int
- var indexName, colName, uniqueness string
-
- err = rows.Scan(&colName, &uniqueness, &indexName)
- if err != nil {
- return nil, err
- }
-
- indexName = strings.Trim(indexName, `" `)
-
- var isRegular bool
- if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
- indexName = indexName[5+len(tableName):]
- isRegular = true
- }
-
- if uniqueness == "UNIQUE" {
- indexType = core.UniqueType
- } else {
- indexType = core.IndexType
- }
-
- var index *core.Index
- var ok bool
- if index, ok = indexes[indexName]; !ok {
- index = new(core.Index)
- index.Type = indexType
- index.Name = indexName
- index.IsRegular = isRegular
- indexes[indexName] = index
- }
- index.AddColumn(colName)
- }
- return indexes, nil
-}
-
-func (db *oracle) Filters() []core.Filter {
- return []core.Filter{&core.QuoteFilter{}, &core.SeqFilter{Prefix: ":", Start: 1}, &core.IdFilter{}}
-}
-
-type goracleDriver struct {
-}
-
-func (cfg *goracleDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- db := &core.Uri{DbType: core.ORACLE}
- dsnPattern := regexp.MustCompile(
- `^(?:(?P.*?)(?::(?P.*))?@)?` + // [user[:password]@]
- `(?:(?P[^\(]*)(?:\((?P[^\)]*)\))?)?` + // [net[(addr)]]
- `\/(?P.*?)` + // /dbname
- `(?:\?(?P[^\?]*))?$`) // [?param1=value1¶mN=valueN]
- matches := dsnPattern.FindStringSubmatch(dataSourceName)
- //tlsConfigRegister := make(map[string]*tls.Config)
- names := dsnPattern.SubexpNames()
-
- for i, match := range matches {
- switch names[i] {
- case "dbname":
- db.DbName = match
- }
- }
- if db.DbName == "" {
- return nil, errors.New("dbname is empty")
- }
- return db, nil
-}
-
-type oci8Driver struct {
-}
-
-//dataSourceName=user/password@ipv4:port/dbname
-//dataSourceName=user/password@[ipv6]:port/dbname
-func (p *oci8Driver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- db := &core.Uri{DbType: core.ORACLE}
- dsnPattern := regexp.MustCompile(
- `^(?P.*)\/(?P.*)@` + // user:password@
- `(?P.*)` + // ip:port
- `\/(?P.*)`) // dbname
- matches := dsnPattern.FindStringSubmatch(dataSourceName)
- names := dsnPattern.SubexpNames()
- for i, match := range matches {
- switch names[i] {
- case "dbname":
- db.DbName = match
- }
- }
- if db.DbName == "" {
- return nil, errors.New("dbname is empty")
- }
- return db, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/dialect_postgres.go b/vendor/github.com/go-xorm/xorm/dialect_postgres.go
deleted file mode 100644
index 662f640..0000000
--- a/vendor/github.com/go-xorm/xorm/dialect_postgres.go
+++ /dev/null
@@ -1,1253 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "net/url"
- "strconv"
- "strings"
-
- "xorm.io/core"
-)
-
-// from http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html
-var (
- postgresReservedWords = map[string]bool{
- "A": true,
- "ABORT": true,
- "ABS": true,
- "ABSENT": true,
- "ABSOLUTE": true,
- "ACCESS": true,
- "ACCORDING": true,
- "ACTION": true,
- "ADA": true,
- "ADD": true,
- "ADMIN": true,
- "AFTER": true,
- "AGGREGATE": true,
- "ALL": true,
- "ALLOCATE": true,
- "ALSO": true,
- "ALTER": true,
- "ALWAYS": true,
- "ANALYSE": true,
- "ANALYZE": true,
- "AND": true,
- "ANY": true,
- "ARE": true,
- "ARRAY": true,
- "ARRAY_AGG": true,
- "ARRAY_MAX_CARDINALITY": true,
- "AS": true,
- "ASC": true,
- "ASENSITIVE": true,
- "ASSERTION": true,
- "ASSIGNMENT": true,
- "ASYMMETRIC": true,
- "AT": true,
- "ATOMIC": true,
- "ATTRIBUTE": true,
- "ATTRIBUTES": true,
- "AUTHORIZATION": true,
- "AVG": true,
- "BACKWARD": true,
- "BASE64": true,
- "BEFORE": true,
- "BEGIN": true,
- "BEGIN_FRAME": true,
- "BEGIN_PARTITION": true,
- "BERNOULLI": true,
- "BETWEEN": true,
- "BIGINT": true,
- "BINARY": true,
- "BIT": true,
- "BIT_LENGTH": true,
- "BLOB": true,
- "BLOCKED": true,
- "BOM": true,
- "BOOLEAN": true,
- "BOTH": true,
- "BREADTH": true,
- "BY": true,
- "C": true,
- "CACHE": true,
- "CALL": true,
- "CALLED": true,
- "CARDINALITY": true,
- "CASCADE": true,
- "CASCADED": true,
- "CASE": true,
- "CAST": true,
- "CATALOG": true,
- "CATALOG_NAME": true,
- "CEIL": true,
- "CEILING": true,
- "CHAIN": true,
- "CHAR": true,
- "CHARACTER": true,
- "CHARACTERISTICS": true,
- "CHARACTERS": true,
- "CHARACTER_LENGTH": true,
- "CHARACTER_SET_CATALOG": true,
- "CHARACTER_SET_NAME": true,
- "CHARACTER_SET_SCHEMA": true,
- "CHAR_LENGTH": true,
- "CHECK": true,
- "CHECKPOINT": true,
- "CLASS": true,
- "CLASS_ORIGIN": true,
- "CLOB": true,
- "CLOSE": true,
- "CLUSTER": true,
- "COALESCE": true,
- "COBOL": true,
- "COLLATE": true,
- "COLLATION": true,
- "COLLATION_CATALOG": true,
- "COLLATION_NAME": true,
- "COLLATION_SCHEMA": true,
- "COLLECT": true,
- "COLUMN": true,
- "COLUMNS": true,
- "COLUMN_NAME": true,
- "COMMAND_FUNCTION": true,
- "COMMAND_FUNCTION_CODE": true,
- "COMMENT": true,
- "COMMENTS": true,
- "COMMIT": true,
- "COMMITTED": true,
- "CONCURRENTLY": true,
- "CONDITION": true,
- "CONDITION_NUMBER": true,
- "CONFIGURATION": true,
- "CONNECT": true,
- "CONNECTION": true,
- "CONNECTION_NAME": true,
- "CONSTRAINT": true,
- "CONSTRAINTS": true,
- "CONSTRAINT_CATALOG": true,
- "CONSTRAINT_NAME": true,
- "CONSTRAINT_SCHEMA": true,
- "CONSTRUCTOR": true,
- "CONTAINS": true,
- "CONTENT": true,
- "CONTINUE": true,
- "CONTROL": true,
- "CONVERSION": true,
- "CONVERT": true,
- "COPY": true,
- "CORR": true,
- "CORRESPONDING": true,
- "COST": true,
- "COUNT": true,
- "COVAR_POP": true,
- "COVAR_SAMP": true,
- "CREATE": true,
- "CROSS": true,
- "CSV": true,
- "CUBE": true,
- "CUME_DIST": true,
- "CURRENT": true,
- "CURRENT_CATALOG": true,
- "CURRENT_DATE": true,
- "CURRENT_DEFAULT_TRANSFORM_GROUP": true,
- "CURRENT_PATH": true,
- "CURRENT_ROLE": true,
- "CURRENT_ROW": true,
- "CURRENT_SCHEMA": true,
- "CURRENT_TIME": true,
- "CURRENT_TIMESTAMP": true,
- "CURRENT_TRANSFORM_GROUP_FOR_TYPE": true,
- "CURRENT_USER": true,
- "CURSOR": true,
- "CURSOR_NAME": true,
- "CYCLE": true,
- "DATA": true,
- "DATABASE": true,
- "DATALINK": true,
- "DATE": true,
- "DATETIME_INTERVAL_CODE": true,
- "DATETIME_INTERVAL_PRECISION": true,
- "DAY": true,
- "DB": true,
- "DEALLOCATE": true,
- "DEC": true,
- "DECIMAL": true,
- "DECLARE": true,
- "DEFAULT": true,
- "DEFAULTS": true,
- "DEFERRABLE": true,
- "DEFERRED": true,
- "DEFINED": true,
- "DEFINER": true,
- "DEGREE": true,
- "DELETE": true,
- "DELIMITER": true,
- "DELIMITERS": true,
- "DENSE_RANK": true,
- "DEPTH": true,
- "DEREF": true,
- "DERIVED": true,
- "DESC": true,
- "DESCRIBE": true,
- "DESCRIPTOR": true,
- "DETERMINISTIC": true,
- "DIAGNOSTICS": true,
- "DICTIONARY": true,
- "DISABLE": true,
- "DISCARD": true,
- "DISCONNECT": true,
- "DISPATCH": true,
- "DISTINCT": true,
- "DLNEWCOPY": true,
- "DLPREVIOUSCOPY": true,
- "DLURLCOMPLETE": true,
- "DLURLCOMPLETEONLY": true,
- "DLURLCOMPLETEWRITE": true,
- "DLURLPATH": true,
- "DLURLPATHONLY": true,
- "DLURLPATHWRITE": true,
- "DLURLSCHEME": true,
- "DLURLSERVER": true,
- "DLVALUE": true,
- "DO": true,
- "DOCUMENT": true,
- "DOMAIN": true,
- "DOUBLE": true,
- "DROP": true,
- "DYNAMIC": true,
- "DYNAMIC_FUNCTION": true,
- "DYNAMIC_FUNCTION_CODE": true,
- "EACH": true,
- "ELEMENT": true,
- "ELSE": true,
- "EMPTY": true,
- "ENABLE": true,
- "ENCODING": true,
- "ENCRYPTED": true,
- "END": true,
- "END-EXEC": true,
- "END_FRAME": true,
- "END_PARTITION": true,
- "ENFORCED": true,
- "ENUM": true,
- "EQUALS": true,
- "ESCAPE": true,
- "EVENT": true,
- "EVERY": true,
- "EXCEPT": true,
- "EXCEPTION": true,
- "EXCLUDE": true,
- "EXCLUDING": true,
- "EXCLUSIVE": true,
- "EXEC": true,
- "EXECUTE": true,
- "EXISTS": true,
- "EXP": true,
- "EXPLAIN": true,
- "EXPRESSION": true,
- "EXTENSION": true,
- "EXTERNAL": true,
- "EXTRACT": true,
- "FALSE": true,
- "FAMILY": true,
- "FETCH": true,
- "FILE": true,
- "FILTER": true,
- "FINAL": true,
- "FIRST": true,
- "FIRST_VALUE": true,
- "FLAG": true,
- "FLOAT": true,
- "FLOOR": true,
- "FOLLOWING": true,
- "FOR": true,
- "FORCE": true,
- "FOREIGN": true,
- "FORTRAN": true,
- "FORWARD": true,
- "FOUND": true,
- "FRAME_ROW": true,
- "FREE": true,
- "FREEZE": true,
- "FROM": true,
- "FS": true,
- "FULL": true,
- "FUNCTION": true,
- "FUNCTIONS": true,
- "FUSION": true,
- "G": true,
- "GENERAL": true,
- "GENERATED": true,
- "GET": true,
- "GLOBAL": true,
- "GO": true,
- "GOTO": true,
- "GRANT": true,
- "GRANTED": true,
- "GREATEST": true,
- "GROUP": true,
- "GROUPING": true,
- "GROUPS": true,
- "HANDLER": true,
- "HAVING": true,
- "HEADER": true,
- "HEX": true,
- "HIERARCHY": true,
- "HOLD": true,
- "HOUR": true,
- "ID": true,
- "IDENTITY": true,
- "IF": true,
- "IGNORE": true,
- "ILIKE": true,
- "IMMEDIATE": true,
- "IMMEDIATELY": true,
- "IMMUTABLE": true,
- "IMPLEMENTATION": true,
- "IMPLICIT": true,
- "IMPORT": true,
- "IN": true,
- "INCLUDING": true,
- "INCREMENT": true,
- "INDENT": true,
- "INDEX": true,
- "INDEXES": true,
- "INDICATOR": true,
- "INHERIT": true,
- "INHERITS": true,
- "INITIALLY": true,
- "INLINE": true,
- "INNER": true,
- "INOUT": true,
- "INPUT": true,
- "INSENSITIVE": true,
- "INSERT": true,
- "INSTANCE": true,
- "INSTANTIABLE": true,
- "INSTEAD": true,
- "INT": true,
- "INTEGER": true,
- "INTEGRITY": true,
- "INTERSECT": true,
- "INTERSECTION": true,
- "INTERVAL": true,
- "INTO": true,
- "INVOKER": true,
- "IS": true,
- "ISNULL": true,
- "ISOLATION": true,
- "JOIN": true,
- "K": true,
- "KEY": true,
- "KEY_MEMBER": true,
- "KEY_TYPE": true,
- "LABEL": true,
- "LAG": true,
- "LANGUAGE": true,
- "LARGE": true,
- "LAST": true,
- "LAST_VALUE": true,
- "LATERAL": true,
- "LC_COLLATE": true,
- "LC_CTYPE": true,
- "LEAD": true,
- "LEADING": true,
- "LEAKPROOF": true,
- "LEAST": true,
- "LEFT": true,
- "LENGTH": true,
- "LEVEL": true,
- "LIBRARY": true,
- "LIKE": true,
- "LIKE_REGEX": true,
- "LIMIT": true,
- "LINK": true,
- "LISTEN": true,
- "LN": true,
- "LOAD": true,
- "LOCAL": true,
- "LOCALTIME": true,
- "LOCALTIMESTAMP": true,
- "LOCATION": true,
- "LOCATOR": true,
- "LOCK": true,
- "LOWER": true,
- "M": true,
- "MAP": true,
- "MAPPING": true,
- "MATCH": true,
- "MATCHED": true,
- "MATERIALIZED": true,
- "MAX": true,
- "MAXVALUE": true,
- "MAX_CARDINALITY": true,
- "MEMBER": true,
- "MERGE": true,
- "MESSAGE_LENGTH": true,
- "MESSAGE_OCTET_LENGTH": true,
- "MESSAGE_TEXT": true,
- "METHOD": true,
- "MIN": true,
- "MINUTE": true,
- "MINVALUE": true,
- "MOD": true,
- "MODE": true,
- "MODIFIES": true,
- "MODULE": true,
- "MONTH": true,
- "MORE": true,
- "MOVE": true,
- "MULTISET": true,
- "MUMPS": true,
- "NAME": true,
- "NAMES": true,
- "NAMESPACE": true,
- "NATIONAL": true,
- "NATURAL": true,
- "NCHAR": true,
- "NCLOB": true,
- "NESTING": true,
- "NEW": true,
- "NEXT": true,
- "NFC": true,
- "NFD": true,
- "NFKC": true,
- "NFKD": true,
- "NIL": true,
- "NO": true,
- "NONE": true,
- "NORMALIZE": true,
- "NORMALIZED": true,
- "NOT": true,
- "NOTHING": true,
- "NOTIFY": true,
- "NOTNULL": true,
- "NOWAIT": true,
- "NTH_VALUE": true,
- "NTILE": true,
- "NULL": true,
- "NULLABLE": true,
- "NULLIF": true,
- "NULLS": true,
- "NUMBER": true,
- "NUMERIC": true,
- "OBJECT": true,
- "OCCURRENCES_REGEX": true,
- "OCTETS": true,
- "OCTET_LENGTH": true,
- "OF": true,
- "OFF": true,
- "OFFSET": true,
- "OIDS": true,
- "OLD": true,
- "ON": true,
- "ONLY": true,
- "OPEN": true,
- "OPERATOR": true,
- "OPTION": true,
- "OPTIONS": true,
- "OR": true,
- "ORDER": true,
- "ORDERING": true,
- "ORDINALITY": true,
- "OTHERS": true,
- "OUT": true,
- "OUTER": true,
- "OUTPUT": true,
- "OVER": true,
- "OVERLAPS": true,
- "OVERLAY": true,
- "OVERRIDING": true,
- "OWNED": true,
- "OWNER": true,
- "P": true,
- "PAD": true,
- "PARAMETER": true,
- "PARAMETER_MODE": true,
- "PARAMETER_NAME": true,
- "PARAMETER_ORDINAL_POSITION": true,
- "PARAMETER_SPECIFIC_CATALOG": true,
- "PARAMETER_SPECIFIC_NAME": true,
- "PARAMETER_SPECIFIC_SCHEMA": true,
- "PARSER": true,
- "PARTIAL": true,
- "PARTITION": true,
- "PASCAL": true,
- "PASSING": true,
- "PASSTHROUGH": true,
- "PASSWORD": true,
- "PATH": true,
- "PERCENT": true,
- "PERCENTILE_CONT": true,
- "PERCENTILE_DISC": true,
- "PERCENT_RANK": true,
- "PERIOD": true,
- "PERMISSION": true,
- "PLACING": true,
- "PLANS": true,
- "PLI": true,
- "PORTION": true,
- "POSITION": true,
- "POSITION_REGEX": true,
- "POWER": true,
- "PRECEDES": true,
- "PRECEDING": true,
- "PRECISION": true,
- "PREPARE": true,
- "PREPARED": true,
- "PRESERVE": true,
- "PRIMARY": true,
- "PRIOR": true,
- "PRIVILEGES": true,
- "PROCEDURAL": true,
- "PROCEDURE": true,
- "PROGRAM": true,
- "PUBLIC": true,
- "QUOTE": true,
- "RANGE": true,
- "RANK": true,
- "READ": true,
- "READS": true,
- "REAL": true,
- "REASSIGN": true,
- "RECHECK": true,
- "RECOVERY": true,
- "RECURSIVE": true,
- "REF": true,
- "REFERENCES": true,
- "REFERENCING": true,
- "REFRESH": true,
- "REGR_AVGX": true,
- "REGR_AVGY": true,
- "REGR_COUNT": true,
- "REGR_INTERCEPT": true,
- "REGR_R2": true,
- "REGR_SLOPE": true,
- "REGR_SXX": true,
- "REGR_SXY": true,
- "REGR_SYY": true,
- "REINDEX": true,
- "RELATIVE": true,
- "RELEASE": true,
- "RENAME": true,
- "REPEATABLE": true,
- "REPLACE": true,
- "REPLICA": true,
- "REQUIRING": true,
- "RESET": true,
- "RESPECT": true,
- "RESTART": true,
- "RESTORE": true,
- "RESTRICT": true,
- "RESULT": true,
- "RETURN": true,
- "RETURNED_CARDINALITY": true,
- "RETURNED_LENGTH": true,
- "RETURNED_OCTET_LENGTH": true,
- "RETURNED_SQLSTATE": true,
- "RETURNING": true,
- "RETURNS": true,
- "REVOKE": true,
- "RIGHT": true,
- "ROLE": true,
- "ROLLBACK": true,
- "ROLLUP": true,
- "ROUTINE": true,
- "ROUTINE_CATALOG": true,
- "ROUTINE_NAME": true,
- "ROUTINE_SCHEMA": true,
- "ROW": true,
- "ROWS": true,
- "ROW_COUNT": true,
- "ROW_NUMBER": true,
- "RULE": true,
- "SAVEPOINT": true,
- "SCALE": true,
- "SCHEMA": true,
- "SCHEMA_NAME": true,
- "SCOPE": true,
- "SCOPE_CATALOG": true,
- "SCOPE_NAME": true,
- "SCOPE_SCHEMA": true,
- "SCROLL": true,
- "SEARCH": true,
- "SECOND": true,
- "SECTION": true,
- "SECURITY": true,
- "SELECT": true,
- "SELECTIVE": true,
- "SELF": true,
- "SENSITIVE": true,
- "SEQUENCE": true,
- "SEQUENCES": true,
- "SERIALIZABLE": true,
- "SERVER": true,
- "SERVER_NAME": true,
- "SESSION": true,
- "SESSION_USER": true,
- "SET": true,
- "SETOF": true,
- "SETS": true,
- "SHARE": true,
- "SHOW": true,
- "SIMILAR": true,
- "SIMPLE": true,
- "SIZE": true,
- "SMALLINT": true,
- "SNAPSHOT": true,
- "SOME": true,
- "SOURCE": true,
- "SPACE": true,
- "SPECIFIC": true,
- "SPECIFICTYPE": true,
- "SPECIFIC_NAME": true,
- "SQL": true,
- "SQLCODE": true,
- "SQLERROR": true,
- "SQLEXCEPTION": true,
- "SQLSTATE": true,
- "SQLWARNING": true,
- "SQRT": true,
- "STABLE": true,
- "STANDALONE": true,
- "START": true,
- "STATE": true,
- "STATEMENT": true,
- "STATIC": true,
- "STATISTICS": true,
- "STDDEV_POP": true,
- "STDDEV_SAMP": true,
- "STDIN": true,
- "STDOUT": true,
- "STORAGE": true,
- "STRICT": true,
- "STRIP": true,
- "STRUCTURE": true,
- "STYLE": true,
- "SUBCLASS_ORIGIN": true,
- "SUBMULTISET": true,
- "SUBSTRING": true,
- "SUBSTRING_REGEX": true,
- "SUCCEEDS": true,
- "SUM": true,
- "SYMMETRIC": true,
- "SYSID": true,
- "SYSTEM": true,
- "SYSTEM_TIME": true,
- "SYSTEM_USER": true,
- "T": true,
- "TABLE": true,
- "TABLES": true,
- "TABLESAMPLE": true,
- "TABLESPACE": true,
- "TABLE_NAME": true,
- "TEMP": true,
- "TEMPLATE": true,
- "TEMPORARY": true,
- "TEXT": true,
- "THEN": true,
- "TIES": true,
- "TIME": true,
- "TIMESTAMP": true,
- "TIMEZONE_HOUR": true,
- "TIMEZONE_MINUTE": true,
- "TO": true,
- "TOKEN": true,
- "TOP_LEVEL_COUNT": true,
- "TRAILING": true,
- "TRANSACTION": true,
- "TRANSACTIONS_COMMITTED": true,
- "TRANSACTIONS_ROLLED_BACK": true,
- "TRANSACTION_ACTIVE": true,
- "TRANSFORM": true,
- "TRANSFORMS": true,
- "TRANSLATE": true,
- "TRANSLATE_REGEX": true,
- "TRANSLATION": true,
- "TREAT": true,
- "TRIGGER": true,
- "TRIGGER_CATALOG": true,
- "TRIGGER_NAME": true,
- "TRIGGER_SCHEMA": true,
- "TRIM": true,
- "TRIM_ARRAY": true,
- "TRUE": true,
- "TRUNCATE": true,
- "TRUSTED": true,
- "TYPE": true,
- "TYPES": true,
- "UESCAPE": true,
- "UNBOUNDED": true,
- "UNCOMMITTED": true,
- "UNDER": true,
- "UNENCRYPTED": true,
- "UNION": true,
- "UNIQUE": true,
- "UNKNOWN": true,
- "UNLINK": true,
- "UNLISTEN": true,
- "UNLOGGED": true,
- "UNNAMED": true,
- "UNNEST": true,
- "UNTIL": true,
- "UNTYPED": true,
- "UPDATE": true,
- "UPPER": true,
- "URI": true,
- "USAGE": true,
- "USER": true,
- "USER_DEFINED_TYPE_CATALOG": true,
- "USER_DEFINED_TYPE_CODE": true,
- "USER_DEFINED_TYPE_NAME": true,
- "USER_DEFINED_TYPE_SCHEMA": true,
- "USING": true,
- "VACUUM": true,
- "VALID": true,
- "VALIDATE": true,
- "VALIDATOR": true,
- "VALUE": true,
- "VALUES": true,
- "VALUE_OF": true,
- "VARBINARY": true,
- "VARCHAR": true,
- "VARIADIC": true,
- "VARYING": true,
- "VAR_POP": true,
- "VAR_SAMP": true,
- "VERBOSE": true,
- "VERSION": true,
- "VERSIONING": true,
- "VIEW": true,
- "VOLATILE": true,
- "WHEN": true,
- "WHENEVER": true,
- "WHERE": true,
- "WHITESPACE": true,
- "WIDTH_BUCKET": true,
- "WINDOW": true,
- "WITH": true,
- "WITHIN": true,
- "WITHOUT": true,
- "WORK": true,
- "WRAPPER": true,
- "WRITE": true,
- "XML": true,
- "XMLAGG": true,
- "XMLATTRIBUTES": true,
- "XMLBINARY": true,
- "XMLCAST": true,
- "XMLCOMMENT": true,
- "XMLCONCAT": true,
- "XMLDECLARATION": true,
- "XMLDOCUMENT": true,
- "XMLELEMENT": true,
- "XMLEXISTS": true,
- "XMLFOREST": true,
- "XMLITERATE": true,
- "XMLNAMESPACES": true,
- "XMLPARSE": true,
- "XMLPI": true,
- "XMLQUERY": true,
- "XMLROOT": true,
- "XMLSCHEMA": true,
- "XMLSERIALIZE": true,
- "XMLTABLE": true,
- "XMLTEXT": true,
- "XMLVALIDATE": true,
- "YEAR": true,
- "YES": true,
- "ZONE": true,
- }
-
- // DefaultPostgresSchema default postgres schema
- DefaultPostgresSchema = "public"
-)
-
-const postgresPublicSchema = "public"
-
-type postgres struct {
- core.Base
-}
-
-func (db *postgres) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
- err := db.Base.Init(d, db, uri, drivername, dataSourceName)
- if err != nil {
- return err
- }
- if db.Schema == "" {
- db.Schema = DefaultPostgresSchema
- }
- return nil
-}
-
-func (db *postgres) SqlType(c *core.Column) string {
- var res string
- switch t := c.SQLType.Name; t {
- case core.TinyInt:
- res = core.SmallInt
- return res
- case core.Bit:
- res = core.Boolean
- return res
- case core.MediumInt, core.Int, core.Integer:
- if c.IsAutoIncrement {
- return core.Serial
- }
- return core.Integer
- case core.BigInt:
- if c.IsAutoIncrement {
- return core.BigSerial
- }
- return core.BigInt
- case core.Serial, core.BigSerial:
- c.IsAutoIncrement = true
- c.Nullable = false
- res = t
- case core.Binary, core.VarBinary:
- return core.Bytea
- case core.DateTime:
- res = core.TimeStamp
- case core.TimeStampz:
- return "timestamp with time zone"
- case core.Float:
- res = core.Real
- case core.TinyText, core.MediumText, core.LongText:
- res = core.Text
- case core.NVarchar:
- res = core.Varchar
- case core.Uuid:
- return core.Uuid
- case core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob:
- return core.Bytea
- case core.Double:
- return "DOUBLE PRECISION"
- default:
- if c.IsAutoIncrement {
- return core.Serial
- }
- res = t
- }
-
- if strings.EqualFold(res, "bool") {
- // for bool, we don't need length information
- return res
- }
- hasLen1 := (c.Length > 0)
- hasLen2 := (c.Length2 > 0)
-
- if hasLen2 {
- res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
- } else if hasLen1 {
- res += "(" + strconv.Itoa(c.Length) + ")"
- }
- return res
-}
-
-func (db *postgres) SupportInsertMany() bool {
- return true
-}
-
-func (db *postgres) IsReserved(name string) bool {
- _, ok := postgresReservedWords[name]
- return ok
-}
-
-func (db *postgres) Quote(name string) string {
- name = strings.Replace(name, ".", `"."`, -1)
- return "\"" + name + "\""
-}
-
-func (db *postgres) QuoteStr() string {
- return "\""
-}
-
-func (db *postgres) AutoIncrStr() string {
- return ""
-}
-
-func (db *postgres) SupportEngine() bool {
- return false
-}
-
-func (db *postgres) SupportCharset() bool {
- return false
-}
-
-func (db *postgres) IndexOnTable() bool {
- return false
-}
-
-func (db *postgres) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
- if len(db.Schema) == 0 {
- args := []interface{}{tableName, idxName}
- return `SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?`, args
- }
-
- args := []interface{}{db.Schema, tableName, idxName}
- return `SELECT indexname FROM pg_indexes ` +
- `WHERE schemaname = ? AND tablename = ? AND indexname = ?`, args
-}
-
-func (db *postgres) TableCheckSql(tableName string) (string, []interface{}) {
- if len(db.Schema) == 0 {
- args := []interface{}{tableName}
- return `SELECT tablename FROM pg_tables WHERE tablename = ?`, args
- }
-
- args := []interface{}{db.Schema, tableName}
- return `SELECT tablename FROM pg_tables WHERE schemaname = ? AND tablename = ?`, args
-}
-
-func (db *postgres) ModifyColumnSql(tableName string, col *core.Column) string {
- if len(db.Schema) == 0 {
- return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s",
- tableName, col.Name, db.SqlType(col))
- }
- return fmt.Sprintf("alter table %s.%s ALTER COLUMN %s TYPE %s",
- db.Schema, tableName, col.Name, db.SqlType(col))
-}
-
-func (db *postgres) DropIndexSql(tableName string, index *core.Index) string {
- quote := db.Quote
- idxName := index.Name
-
- tableName = strings.Replace(tableName, `"`, "", -1)
- tableName = strings.Replace(tableName, `.`, "_", -1)
-
- if !strings.HasPrefix(idxName, "UQE_") &&
- !strings.HasPrefix(idxName, "IDX_") {
- if index.Type == core.UniqueType {
- idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
- } else {
- idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
- }
- }
- if db.Uri.Schema != "" {
- idxName = db.Uri.Schema + "." + idxName
- }
- return fmt.Sprintf("DROP INDEX %v", quote(idxName))
-}
-
-func (db *postgres) IsColumnExist(tableName, colName string) (bool, error) {
- args := []interface{}{db.Schema, tableName, colName}
- query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = $1 AND table_name = $2" +
- " AND column_name = $3"
- if len(db.Schema) == 0 {
- args = []interface{}{tableName, colName}
- query = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" +
- " AND column_name = $2"
- }
- db.LogSQL(query, args)
-
- rows, err := db.DB().Query(query, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- return rows.Next(), nil
-}
-
-func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
- args := []interface{}{tableName}
- s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix ,
- CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
- CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey
-FROM pg_attribute f
- JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid
- LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
- LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
- LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
- LEFT JOIN pg_class AS g ON p.confrelid = g.oid
- LEFT JOIN INFORMATION_SCHEMA.COLUMNS s ON s.column_name=f.attname AND c.relname=s.table_name
-WHERE c.relkind = 'r'::char AND c.relname = $1%s AND f.attnum > 0 ORDER BY f.attnum;`
-
- var f string
- if len(db.Schema) != 0 {
- args = append(args, db.Schema)
- f = " AND s.table_schema = $2"
- }
- s = fmt.Sprintf(s, f)
-
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, nil, err
- }
- defer rows.Close()
-
- cols := make(map[string]*core.Column)
- colSeq := make([]string, 0)
-
- for rows.Next() {
- col := new(core.Column)
- col.Indexes = make(map[string]int)
-
- var colName, isNullable, dataType string
- var maxLenStr, colDefault, numPrecision, numRadix *string
- var isPK, isUnique bool
- err = rows.Scan(&colName, &colDefault, &isNullable, &dataType, &maxLenStr, &numPrecision, &numRadix, &isPK, &isUnique)
- if err != nil {
- return nil, nil, err
- }
-
- //fmt.Println(args, colName, isNullable, dataType, maxLenStr, colDefault, numPrecision, numRadix, isPK, isUnique)
- var maxLen int
- if maxLenStr != nil {
- maxLen, err = strconv.Atoi(*maxLenStr)
- if err != nil {
- return nil, nil, err
- }
- }
-
- col.Name = strings.Trim(colName, `" `)
-
- if colDefault != nil || isPK {
- if isPK {
- col.IsPrimaryKey = true
- } else {
- col.Default = *colDefault
- }
- }
-
- if colDefault != nil && strings.HasPrefix(*colDefault, "nextval(") {
- col.IsAutoIncrement = true
- }
-
- col.Nullable = (isNullable == "YES")
-
- switch dataType {
- case "character varying", "character":
- col.SQLType = core.SQLType{Name: core.Varchar, DefaultLength: 0, DefaultLength2: 0}
- case "timestamp without time zone":
- col.SQLType = core.SQLType{Name: core.DateTime, DefaultLength: 0, DefaultLength2: 0}
- case "timestamp with time zone":
- col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
- case "double precision":
- col.SQLType = core.SQLType{Name: core.Double, DefaultLength: 0, DefaultLength2: 0}
- case "boolean":
- col.SQLType = core.SQLType{Name: core.Bool, DefaultLength: 0, DefaultLength2: 0}
- case "time without time zone":
- col.SQLType = core.SQLType{Name: core.Time, DefaultLength: 0, DefaultLength2: 0}
- case "oid":
- col.SQLType = core.SQLType{Name: core.BigInt, DefaultLength: 0, DefaultLength2: 0}
- default:
- col.SQLType = core.SQLType{Name: strings.ToUpper(dataType), DefaultLength: 0, DefaultLength2: 0}
- }
- if _, ok := core.SqlTypes[col.SQLType.Name]; !ok {
- return nil, nil, fmt.Errorf("Unknown colType: %v", dataType)
- }
-
- col.Length = maxLen
-
- if col.SQLType.IsText() || col.SQLType.IsTime() {
- if col.Default != "" {
- col.Default = "'" + col.Default + "'"
- } else {
- if col.DefaultIsEmpty {
- col.Default = "''"
- }
- }
- }
- cols[col.Name] = col
- colSeq = append(colSeq, col.Name)
- }
-
- return colSeq, cols, nil
-}
-
-func (db *postgres) GetTables() ([]*core.Table, error) {
- args := []interface{}{}
- s := "SELECT tablename FROM pg_tables"
- if len(db.Schema) != 0 {
- args = append(args, db.Schema)
- s = s + " WHERE schemaname = $1"
- }
-
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- tables := make([]*core.Table, 0)
- for rows.Next() {
- table := core.NewEmptyTable()
- var name string
- err = rows.Scan(&name)
- if err != nil {
- return nil, err
- }
- table.Name = name
- tables = append(tables, table)
- }
- return tables, nil
-}
-
-
-func getIndexColName(indexdef string) []string {
- var colNames []string
-
- cs := strings.Split(indexdef, "(")
- for _, v := range strings.Split(strings.Split(cs[1], ")")[0], ",") {
- colNames = append(colNames, strings.Split(strings.TrimLeft(v, " "), " ")[0])
- }
-
- return colNames
-}
-
-
-func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) {
- args := []interface{}{tableName}
- s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE tablename=$1")
- if len(db.Schema) != 0 {
- args = append(args, db.Schema)
- s = s + " AND schemaname=$2"
- }
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- indexes := make(map[string]*core.Index, 0)
- for rows.Next() {
- var indexType int
- var indexName, indexdef string
- var colNames []string
- err = rows.Scan(&indexName, &indexdef)
- if err != nil {
- return nil, err
- }
- indexName = strings.Trim(indexName, `" `)
- if strings.HasSuffix(indexName, "_pkey") {
- continue
- }
- if strings.HasPrefix(indexdef, "CREATE UNIQUE INDEX") {
- indexType = core.UniqueType
- } else {
- indexType = core.IndexType
- }
- colNames = getIndexColName(indexdef)
- var isRegular bool
- if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
- newIdxName := indexName[5+len(tableName):]
- isRegular = true
- if newIdxName != "" {
- indexName = newIdxName
- }
- }
-
- index := &core.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)}
- for _, colName := range colNames {
- index.Cols = append(index.Cols, strings.Trim(colName, `" `))
- }
- index.IsRegular = isRegular
- indexes[index.Name] = index
- }
- return indexes, nil
-}
-
-func (db *postgres) Filters() []core.Filter {
- return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}, &core.SeqFilter{Prefix: "$", Start: 1}}
-}
-
-type pqDriver struct {
-}
-
-type values map[string]string
-
-func (vs values) Set(k, v string) {
- vs[k] = v
-}
-
-func (vs values) Get(k string) (v string) {
- return vs[k]
-}
-
-func parseURL(connstr string) (string, error) {
- u, err := url.Parse(connstr)
- if err != nil {
- return "", err
- }
-
- if u.Scheme != "postgresql" && u.Scheme != "postgres" {
- return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
- }
-
- escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
-
- if u.Path != "" {
- return escaper.Replace(u.Path[1:]), nil
- }
-
- return "", nil
-}
-
-func parseOpts(name string, o values) error {
- if len(name) == 0 {
- return fmt.Errorf("invalid options: %s", name)
- }
-
- name = strings.TrimSpace(name)
-
- ps := strings.Split(name, " ")
- for _, p := range ps {
- kv := strings.Split(p, "=")
- if len(kv) < 2 {
- return fmt.Errorf("invalid option: %q", p)
- }
- o.Set(kv[0], kv[1])
- }
-
- return nil
-}
-
-func (p *pqDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- db := &core.Uri{DbType: core.POSTGRES}
- var err error
-
- if strings.HasPrefix(dataSourceName, "postgresql://") || strings.HasPrefix(dataSourceName, "postgres://") {
- db.DbName, err = parseURL(dataSourceName)
- if err != nil {
- return nil, err
- }
- } else {
- o := make(values)
- err = parseOpts(dataSourceName, o)
- if err != nil {
- return nil, err
- }
-
- db.DbName = o.Get("dbname")
- }
-
- if db.DbName == "" {
- return nil, errors.New("dbname is empty")
- }
-
- return db, nil
-}
-
-type pqDriverPgx struct {
- pqDriver
-}
-
-func (pgx *pqDriverPgx) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- // Remove the leading characters for driver to work
- if len(dataSourceName) >= 9 && dataSourceName[0] == 0 {
- dataSourceName = dataSourceName[9:]
- }
- return pgx.pqDriver.Parse(driverName, dataSourceName)
-}
diff --git a/vendor/github.com/go-xorm/xorm/dialect_sqlite3.go b/vendor/github.com/go-xorm/xorm/dialect_sqlite3.go
deleted file mode 100644
index e30a775..0000000
--- a/vendor/github.com/go-xorm/xorm/dialect_sqlite3.go
+++ /dev/null
@@ -1,460 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "errors"
- "fmt"
- "regexp"
- "strings"
-
- "xorm.io/core"
-)
-
-var (
- sqlite3ReservedWords = map[string]bool{
- "ABORT": true,
- "ACTION": true,
- "ADD": true,
- "AFTER": true,
- "ALL": true,
- "ALTER": true,
- "ANALYZE": true,
- "AND": true,
- "AS": true,
- "ASC": true,
- "ATTACH": true,
- "AUTOINCREMENT": true,
- "BEFORE": true,
- "BEGIN": true,
- "BETWEEN": true,
- "BY": true,
- "CASCADE": true,
- "CASE": true,
- "CAST": true,
- "CHECK": true,
- "COLLATE": true,
- "COLUMN": true,
- "COMMIT": true,
- "CONFLICT": true,
- "CONSTRAINT": true,
- "CREATE": true,
- "CROSS": true,
- "CURRENT_DATE": true,
- "CURRENT_TIME": true,
- "CURRENT_TIMESTAMP": true,
- "DATABASE": true,
- "DEFAULT": true,
- "DEFERRABLE": true,
- "DEFERRED": true,
- "DELETE": true,
- "DESC": true,
- "DETACH": true,
- "DISTINCT": true,
- "DROP": true,
- "EACH": true,
- "ELSE": true,
- "END": true,
- "ESCAPE": true,
- "EXCEPT": true,
- "EXCLUSIVE": true,
- "EXISTS": true,
- "EXPLAIN": true,
- "FAIL": true,
- "FOR": true,
- "FOREIGN": true,
- "FROM": true,
- "FULL": true,
- "GLOB": true,
- "GROUP": true,
- "HAVING": true,
- "IF": true,
- "IGNORE": true,
- "IMMEDIATE": true,
- "IN": true,
- "INDEX": true,
- "INDEXED": true,
- "INITIALLY": true,
- "INNER": true,
- "INSERT": true,
- "INSTEAD": true,
- "INTERSECT": true,
- "INTO": true,
- "IS": true,
- "ISNULL": true,
- "JOIN": true,
- "KEY": true,
- "LEFT": true,
- "LIKE": true,
- "LIMIT": true,
- "MATCH": true,
- "NATURAL": true,
- "NO": true,
- "NOT": true,
- "NOTNULL": true,
- "NULL": true,
- "OF": true,
- "OFFSET": true,
- "ON": true,
- "OR": true,
- "ORDER": true,
- "OUTER": true,
- "PLAN": true,
- "PRAGMA": true,
- "PRIMARY": true,
- "QUERY": true,
- "RAISE": true,
- "RECURSIVE": true,
- "REFERENCES": true,
- "REGEXP": true,
- "REINDEX": true,
- "RELEASE": true,
- "RENAME": true,
- "REPLACE": true,
- "RESTRICT": true,
- "RIGHT": true,
- "ROLLBACK": true,
- "ROW": true,
- "SAVEPOINT": true,
- "SELECT": true,
- "SET": true,
- "TABLE": true,
- "TEMP": true,
- "TEMPORARY": true,
- "THEN": true,
- "TO": true,
- "TRANSACTI": true,
- "TRIGGER": true,
- "UNION": true,
- "UNIQUE": true,
- "UPDATE": true,
- "USING": true,
- "VACUUM": true,
- "VALUES": true,
- "VIEW": true,
- "VIRTUAL": true,
- "WHEN": true,
- "WHERE": true,
- "WITH": true,
- "WITHOUT": true,
- }
-)
-
-type sqlite3 struct {
- core.Base
-}
-
-func (db *sqlite3) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
- return db.Base.Init(d, db, uri, drivername, dataSourceName)
-}
-
-func (db *sqlite3) SqlType(c *core.Column) string {
- switch t := c.SQLType.Name; t {
- case core.Bool:
- if c.Default == "true" {
- c.Default = "1"
- } else if c.Default == "false" {
- c.Default = "0"
- }
- return core.Integer
- case core.Date, core.DateTime, core.TimeStamp, core.Time:
- return core.DateTime
- case core.TimeStampz:
- return core.Text
- case core.Char, core.Varchar, core.NVarchar, core.TinyText,
- core.Text, core.MediumText, core.LongText, core.Json:
- return core.Text
- case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt:
- return core.Integer
- case core.Float, core.Double, core.Real:
- return core.Real
- case core.Decimal, core.Numeric:
- return core.Numeric
- case core.TinyBlob, core.Blob, core.MediumBlob, core.LongBlob, core.Bytea, core.Binary, core.VarBinary:
- return core.Blob
- case core.Serial, core.BigSerial:
- c.IsPrimaryKey = true
- c.IsAutoIncrement = true
- c.Nullable = false
- return core.Integer
- default:
- return t
- }
-}
-
-func (db *sqlite3) FormatBytes(bs []byte) string {
- return fmt.Sprintf("X'%x'", bs)
-}
-
-func (db *sqlite3) SupportInsertMany() bool {
- return true
-}
-
-func (db *sqlite3) IsReserved(name string) bool {
- _, ok := sqlite3ReservedWords[name]
- return ok
-}
-
-func (db *sqlite3) Quote(name string) string {
- return "`" + name + "`"
-}
-
-func (db *sqlite3) QuoteStr() string {
- return "`"
-}
-
-func (db *sqlite3) AutoIncrStr() string {
- return "AUTOINCREMENT"
-}
-
-func (db *sqlite3) SupportEngine() bool {
- return false
-}
-
-func (db *sqlite3) SupportCharset() bool {
- return false
-}
-
-func (db *sqlite3) IndexOnTable() bool {
- return false
-}
-
-func (db *sqlite3) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
- args := []interface{}{idxName}
- return "SELECT name FROM sqlite_master WHERE type='index' and name = ?", args
-}
-
-func (db *sqlite3) TableCheckSql(tableName string) (string, []interface{}) {
- args := []interface{}{tableName}
- return "SELECT name FROM sqlite_master WHERE type='table' and name = ?", args
-}
-
-func (db *sqlite3) DropIndexSql(tableName string, index *core.Index) string {
- // var unique string
- quote := db.Quote
- idxName := index.Name
-
- if !strings.HasPrefix(idxName, "UQE_") &&
- !strings.HasPrefix(idxName, "IDX_") {
- if index.Type == core.UniqueType {
- idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
- } else {
- idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
- }
- }
- return fmt.Sprintf("DROP INDEX %v", quote(idxName))
-}
-
-func (db *sqlite3) ForUpdateSql(query string) string {
- return query
-}
-
-/*func (db *sqlite3) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
- args := []interface{}{tableName}
- sql := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
- return sql, args
-}*/
-
-func (db *sqlite3) IsColumnExist(tableName, colName string) (bool, error) {
- args := []interface{}{tableName}
- query := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))"
- db.LogSQL(query, args)
- rows, err := db.DB().Query(query, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- if rows.Next() {
- return true, nil
- }
- return false, nil
-}
-
-func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
- args := []interface{}{tableName}
- s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?"
- db.LogSQL(s, args)
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, nil, err
- }
- defer rows.Close()
-
- var name string
- for rows.Next() {
- err = rows.Scan(&name)
- if err != nil {
- return nil, nil, err
- }
- break
- }
-
- if name == "" {
- return nil, nil, errors.New("no table named " + tableName)
- }
-
- nStart := strings.Index(name, "(")
- nEnd := strings.LastIndex(name, ")")
- reg := regexp.MustCompile(`[^\(,\)]*(\([^\(]*\))?`)
- colCreates := reg.FindAllString(name[nStart+1:nEnd], -1)
- cols := make(map[string]*core.Column)
- colSeq := make([]string, 0)
- for _, colStr := range colCreates {
- reg = regexp.MustCompile(`,\s`)
- colStr = reg.ReplaceAllString(colStr, ",")
- if strings.HasPrefix(strings.TrimSpace(colStr), "PRIMARY KEY") {
- parts := strings.Split(strings.TrimSpace(colStr), "(")
- if len(parts) == 2 {
- pkCols := strings.Split(strings.TrimRight(strings.TrimSpace(parts[1]), ")"), ",")
- for _, pk := range pkCols {
- if col, ok := cols[strings.Trim(strings.TrimSpace(pk), "`")]; ok {
- col.IsPrimaryKey = true
- }
- }
- }
- continue
- }
-
- fields := strings.Fields(strings.TrimSpace(colStr))
- col := new(core.Column)
- col.Indexes = make(map[string]int)
- col.Nullable = true
- col.DefaultIsEmpty = true
-
- for idx, field := range fields {
- if idx == 0 {
- col.Name = strings.Trim(strings.Trim(field, "`[] "), `"`)
- continue
- } else if idx == 1 {
- col.SQLType = core.SQLType{Name: field, DefaultLength: 0, DefaultLength2: 0}
- }
- switch field {
- case "PRIMARY":
- col.IsPrimaryKey = true
- case "AUTOINCREMENT":
- col.IsAutoIncrement = true
- case "NULL":
- if fields[idx-1] == "NOT" {
- col.Nullable = false
- } else {
- col.Nullable = true
- }
- case "DEFAULT":
- col.Default = fields[idx+1]
- col.DefaultIsEmpty = false
- }
- }
- if !col.SQLType.IsNumeric() && !col.DefaultIsEmpty {
- col.Default = "'" + col.Default + "'"
- }
- cols[col.Name] = col
- colSeq = append(colSeq, col.Name)
- }
- return colSeq, cols, nil
-}
-
-func (db *sqlite3) GetTables() ([]*core.Table, error) {
- args := []interface{}{}
- s := "SELECT name FROM sqlite_master WHERE type='table'"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- tables := make([]*core.Table, 0)
- for rows.Next() {
- table := core.NewEmptyTable()
- err = rows.Scan(&table.Name)
- if err != nil {
- return nil, err
- }
- if table.Name == "sqlite_sequence" {
- continue
- }
- tables = append(tables, table)
- }
- return tables, nil
-}
-
-func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) {
- args := []interface{}{tableName}
- s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?"
- db.LogSQL(s, args)
-
- rows, err := db.DB().Query(s, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- indexes := make(map[string]*core.Index, 0)
- for rows.Next() {
- var tmpSQL sql.NullString
- err = rows.Scan(&tmpSQL)
- if err != nil {
- return nil, err
- }
-
- if !tmpSQL.Valid {
- continue
- }
- sql := tmpSQL.String
-
- index := new(core.Index)
- nNStart := strings.Index(sql, "INDEX")
- nNEnd := strings.Index(sql, "ON")
- if nNStart == -1 || nNEnd == -1 {
- continue
- }
-
- indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []")
- var isRegular bool
- if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
- index.Name = indexName[5+len(tableName):]
- isRegular = true
- } else {
- index.Name = indexName
- }
-
- if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") {
- index.Type = core.UniqueType
- } else {
- index.Type = core.IndexType
- }
-
- nStart := strings.Index(sql, "(")
- nEnd := strings.Index(sql, ")")
- colIndexes := strings.Split(sql[nStart+1:nEnd], ",")
-
- index.Cols = make([]string, 0)
- for _, col := range colIndexes {
- index.Cols = append(index.Cols, strings.Trim(col, "` []"))
- }
- index.IsRegular = isRegular
- indexes[index.Name] = index
- }
-
- return indexes, nil
-}
-
-func (db *sqlite3) Filters() []core.Filter {
- return []core.Filter{&core.IdFilter{}}
-}
-
-type sqlite3Driver struct {
-}
-
-func (p *sqlite3Driver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
- if strings.Contains(dataSourceName, "?") {
- dataSourceName = dataSourceName[:strings.Index(dataSourceName, "?")]
- }
-
- return &core.Uri{DbType: core.SQLITE, DbName: dataSourceName}, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/doc.go b/vendor/github.com/go-xorm/xorm/doc.go
deleted file mode 100644
index a687e69..0000000
--- a/vendor/github.com/go-xorm/xorm/doc.go
+++ /dev/null
@@ -1,184 +0,0 @@
-// Copyright 2013 - 2016 The XORM Authors. All rights reserved.
-// Use of this source code is governed by a BSD
-// license that can be found in the LICENSE file.
-
-/*
-
-Package xorm is a simple and powerful ORM for Go.
-
-Installation
-
-Make sure you have installed Go 1.6+ and then:
-
- go get github.com/go-xorm/xorm
-
-Create Engine
-
-Firstly, we should new an engine for a database
-
- engine, err := xorm.NewEngine(driverName, dataSourceName)
-
-Method NewEngine's parameters is the same as sql.Open. It depends
-drivers' implementation.
-Generally, one engine for an application is enough. You can set it as package variable.
-
-Raw Methods
-
-XORM also support raw SQL execution:
-
-1. query a SQL string, the returned results is []map[string][]byte
-
- results, err := engine.Query("select * from user")
-
-2. execute a SQL string, the returned results
-
- affected, err := engine.Exec("update user set .... where ...")
-
-ORM Methods
-
-There are 8 major ORM methods and many helpful methods to use to operate database.
-
-1. Insert one or multiple records to database
-
- affected, err := engine.Insert(&struct)
- // INSERT INTO struct () values ()
- affected, err := engine.Insert(&struct1, &struct2)
- // INSERT INTO struct1 () values ()
- // INSERT INTO struct2 () values ()
- affected, err := engine.Insert(&sliceOfStruct)
- // INSERT INTO struct () values (),(),()
- affected, err := engine.Insert(&struct1, &sliceOfStruct2)
- // INSERT INTO struct1 () values ()
- // INSERT INTO struct2 () values (),(),()
-
-2. Query one record or one variable from database
-
- has, err := engine.Get(&user)
- // SELECT * FROM user LIMIT 1
-
- var id int64
- has, err := engine.Table("user").Where("name = ?", name).Get(&id)
- // SELECT id FROM user WHERE name = ? LIMIT 1
-
-3. Query multiple records from database
-
- var sliceOfStructs []Struct
- err := engine.Find(&sliceOfStructs)
- // SELECT * FROM user
-
- var mapOfStructs = make(map[int64]Struct)
- err := engine.Find(&mapOfStructs)
- // SELECT * FROM user
-
- var int64s []int64
- err := engine.Table("user").Cols("id").Find(&int64s)
- // SELECT id FROM user
-
-4. Query multiple records and record by record handle, there two methods, one is Iterate,
-another is Rows
-
- err := engine.Iterate(...)
- // SELECT * FROM user
-
- rows, err := engine.Rows(...)
- // SELECT * FROM user
- defer rows.Close()
- bean := new(Struct)
- for rows.Next() {
- err = rows.Scan(bean)
- }
-
-5. Update one or more records
-
- affected, err := engine.ID(...).Update(&user)
- // UPDATE user SET ...
-
-6. Delete one or more records, Delete MUST has condition
-
- affected, err := engine.Where(...).Delete(&user)
- // DELETE FROM user Where ...
-
-7. Count records
-
- counts, err := engine.Count(&user)
- // SELECT count(*) AS total FROM user
-
- counts, err := engine.SQL("select count(*) FROM user").Count()
- // select count(*) FROM user
-
-8. Sum records
-
- sumFloat64, err := engine.Sum(&user, "id")
- // SELECT sum(id) from user
-
- sumFloat64s, err := engine.Sums(&user, "id1", "id2")
- // SELECT sum(id1), sum(id2) from user
-
- sumInt64s, err := engine.SumsInt(&user, "id1", "id2")
- // SELECT sum(id1), sum(id2) from user
-
-Conditions
-
-The above 8 methods could use with condition methods chainable.
-Attention: the above 8 methods should be the last chainable method.
-
-1. ID, In
-
- engine.ID(1).Get(&user) // for single primary key
- // SELECT * FROM user WHERE id = 1
- engine.ID(core.PK{1, 2}).Get(&user) // for composite primary keys
- // SELECT * FROM user WHERE id1 = 1 AND id2 = 2
- engine.In("id", 1, 2, 3).Find(&users)
- // SELECT * FROM user WHERE id IN (1, 2, 3)
- engine.In("id", []int{1, 2, 3}).Find(&users)
- // SELECT * FROM user WHERE id IN (1, 2, 3)
-
-2. Where, And, Or
-
- engine.Where().And().Or().Find()
- // SELECT * FROM user WHERE (.. AND ..) OR ...
-
-3. OrderBy, Asc, Desc
-
- engine.Asc().Desc().Find()
- // SELECT * FROM user ORDER BY .. ASC, .. DESC
- engine.OrderBy().Find()
- // SELECT * FROM user ORDER BY ..
-
-4. Limit, Top
-
- engine.Limit().Find()
- // SELECT * FROM user LIMIT .. OFFSET ..
- engine.Top(5).Find()
- // SELECT TOP 5 * FROM user // for mssql
- // SELECT * FROM user LIMIT .. OFFSET 0 //for other databases
-
-5. SQL, let you custom SQL
-
- var users []User
- engine.SQL("select * from user").Find(&users)
-
-6. Cols, Omit, Distinct
-
- var users []*User
- engine.Cols("col1, col2").Find(&users)
- // SELECT col1, col2 FROM user
- engine.Cols("col1", "col2").Where().Update(user)
- // UPDATE user set col1 = ?, col2 = ? Where ...
- engine.Omit("col1").Find(&users)
- // SELECT col2, col3 FROM user
- engine.Omit("col1").Insert(&user)
- // INSERT INTO table (non-col1) VALUES ()
- engine.Distinct("col1").Find(&users)
- // SELECT DISTINCT col1 FROM user
-
-7. Join, GroupBy, Having
-
- engine.GroupBy("name").Having("name='xlw'").Find(&users)
- //SELECT * FROM user GROUP BY name HAVING name='xlw'
- engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find(&users)
- //SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id
-
-More usage, please visit http://xorm.io/docs
-*/
-package xorm
diff --git a/vendor/github.com/go-xorm/xorm/engine.go b/vendor/github.com/go-xorm/xorm/engine.go
deleted file mode 100644
index 0c79451..0000000
--- a/vendor/github.com/go-xorm/xorm/engine.go
+++ /dev/null
@@ -1,1644 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "bufio"
- "bytes"
- "context"
- "database/sql"
- "encoding/gob"
- "errors"
- "fmt"
- "io"
- "os"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "time"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-// Engine is the major struct of xorm, it means a database manager.
-// Commonly, an application only need one engine
-type Engine struct {
- db *core.DB
- dialect core.Dialect
-
- ColumnMapper core.IMapper
- TableMapper core.IMapper
- TagIdentifier string
- Tables map[reflect.Type]*core.Table
-
- mutex *sync.RWMutex
- Cacher core.Cacher
-
- showSQL bool
- showExecTime bool
-
- logger core.ILogger
- TZLocation *time.Location // The timezone of the application
- DatabaseTZ *time.Location // The timezone of the database
-
- disableGlobalCache bool
-
- tagHandlers map[string]tagHandler
-
- engineGroup *EngineGroup
-
- cachers map[string]core.Cacher
- cacherLock sync.RWMutex
-
- defaultContext context.Context
-}
-
-func (engine *Engine) setCacher(tableName string, cacher core.Cacher) {
- engine.cacherLock.Lock()
- engine.cachers[tableName] = cacher
- engine.cacherLock.Unlock()
-}
-
-func (engine *Engine) SetCacher(tableName string, cacher core.Cacher) {
- engine.setCacher(tableName, cacher)
-}
-
-func (engine *Engine) getCacher(tableName string) core.Cacher {
- var cacher core.Cacher
- var ok bool
- engine.cacherLock.RLock()
- cacher, ok = engine.cachers[tableName]
- engine.cacherLock.RUnlock()
- if !ok && !engine.disableGlobalCache {
- cacher = engine.Cacher
- }
- return cacher
-}
-
-func (engine *Engine) GetCacher(tableName string) core.Cacher {
- return engine.getCacher(tableName)
-}
-
-// BufferSize sets buffer size for iterate
-func (engine *Engine) BufferSize(size int) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.BufferSize(size)
-}
-
-// CondDeleted returns the conditions whether a record is soft deleted.
-func (engine *Engine) CondDeleted(colName string) builder.Cond {
- if engine.dialect.DBType() == core.MSSQL {
- return builder.IsNull{colName}
- }
- return builder.IsNull{colName}.Or(builder.Eq{colName: zeroTime1})
-}
-
-// ShowSQL show SQL statement or not on logger if log level is great than INFO
-func (engine *Engine) ShowSQL(show ...bool) {
- engine.logger.ShowSQL(show...)
- if len(show) == 0 {
- engine.showSQL = true
- } else {
- engine.showSQL = show[0]
- }
-}
-
-// ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO
-func (engine *Engine) ShowExecTime(show ...bool) {
- if len(show) == 0 {
- engine.showExecTime = true
- } else {
- engine.showExecTime = show[0]
- }
-}
-
-// Logger return the logger interface
-func (engine *Engine) Logger() core.ILogger {
- return engine.logger
-}
-
-// SetLogger set the new logger
-func (engine *Engine) SetLogger(logger core.ILogger) {
- engine.logger = logger
- engine.showSQL = logger.IsShowSQL()
- engine.dialect.SetLogger(logger)
-}
-
-// SetLogLevel sets the logger level
-func (engine *Engine) SetLogLevel(level core.LogLevel) {
- engine.logger.SetLevel(level)
-}
-
-// SetDisableGlobalCache disable global cache or not
-func (engine *Engine) SetDisableGlobalCache(disable bool) {
- if engine.disableGlobalCache != disable {
- engine.disableGlobalCache = disable
- }
-}
-
-// DriverName return the current sql driver's name
-func (engine *Engine) DriverName() string {
- return engine.dialect.DriverName()
-}
-
-// DataSourceName return the current connection string
-func (engine *Engine) DataSourceName() string {
- return engine.dialect.DataSourceName()
-}
-
-// SetMapper set the name mapping rules
-func (engine *Engine) SetMapper(mapper core.IMapper) {
- engine.SetTableMapper(mapper)
- engine.SetColumnMapper(mapper)
-}
-
-// SetTableMapper set the table name mapping rule
-func (engine *Engine) SetTableMapper(mapper core.IMapper) {
- engine.TableMapper = mapper
-}
-
-// SetColumnMapper set the column name mapping rule
-func (engine *Engine) SetColumnMapper(mapper core.IMapper) {
- engine.ColumnMapper = mapper
-}
-
-// SupportInsertMany If engine's database support batch insert records like
-// "insert into user values (name, age), (name, age)".
-// When the return is ture, then engine.Insert(&users) will
-// generate batch sql and exeute.
-func (engine *Engine) SupportInsertMany() bool {
- return engine.dialect.SupportInsertMany()
-}
-
-// QuoteStr Engine's database use which character as quote.
-// mysql, sqlite use ` and postgres use "
-func (engine *Engine) QuoteStr() string {
- return engine.dialect.QuoteStr()
-}
-
-func (engine *Engine) quoteColumns(columnStr string) string {
- columns := strings.Split(columnStr, ",")
- for i := 0; i < len(columns); i++ {
- columns[i] = engine.Quote(strings.TrimSpace(columns[i]))
- }
- return strings.Join(columns, ",")
-}
-
-// Quote Use QuoteStr quote the string sql
-func (engine *Engine) Quote(value string) string {
- value = strings.TrimSpace(value)
- if len(value) == 0 {
- return value
- }
-
- if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
- return value
- }
-
- value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
-
- return engine.dialect.QuoteStr() + value + engine.dialect.QuoteStr()
-}
-
-// QuoteTo quotes string and writes into the buffer
-func (engine *Engine) QuoteTo(buf *builder.StringBuilder, value string) {
- if buf == nil {
- return
- }
-
- value = strings.TrimSpace(value)
- if value == "" {
- return
- }
-
- if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
- buf.WriteString(value)
- return
- }
-
- value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
-
- buf.WriteString(engine.dialect.QuoteStr())
- buf.WriteString(value)
- buf.WriteString(engine.dialect.QuoteStr())
-}
-
-func (engine *Engine) quote(sql string) string {
- return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
-}
-
-// SqlType will be deprecated, please use SQLType instead
-//
-// Deprecated: use SQLType instead
-func (engine *Engine) SqlType(c *core.Column) string {
- return engine.SQLType(c)
-}
-
-// SQLType A simple wrapper to dialect's core.SqlType method
-func (engine *Engine) SQLType(c *core.Column) string {
- return engine.dialect.SqlType(c)
-}
-
-// AutoIncrStr Database's autoincrement statement
-func (engine *Engine) AutoIncrStr() string {
- return engine.dialect.AutoIncrStr()
-}
-
-// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
-func (engine *Engine) SetConnMaxLifetime(d time.Duration) {
- engine.db.SetConnMaxLifetime(d)
-}
-
-// SetMaxOpenConns is only available for go 1.2+
-func (engine *Engine) SetMaxOpenConns(conns int) {
- engine.db.SetMaxOpenConns(conns)
-}
-
-// SetMaxIdleConns set the max idle connections on pool, default is 2
-func (engine *Engine) SetMaxIdleConns(conns int) {
- engine.db.SetMaxIdleConns(conns)
-}
-
-// SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
-func (engine *Engine) SetDefaultCacher(cacher core.Cacher) {
- engine.Cacher = cacher
-}
-
-// GetDefaultCacher returns the default cacher
-func (engine *Engine) GetDefaultCacher() core.Cacher {
- return engine.Cacher
-}
-
-// NoCache If you has set default cacher, and you want temporilly stop use cache,
-// you can use NoCache()
-func (engine *Engine) NoCache() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.NoCache()
-}
-
-// NoCascade If you do not want to auto cascade load object
-func (engine *Engine) NoCascade() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.NoCascade()
-}
-
-// MapCacher Set a table use a special cacher
-func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) error {
- engine.setCacher(engine.TableName(bean, true), cacher)
- return nil
-}
-
-// NewDB provides an interface to operate database directly
-func (engine *Engine) NewDB() (*core.DB, error) {
- return core.OpenDialect(engine.dialect)
-}
-
-// DB return the wrapper of sql.DB
-func (engine *Engine) DB() *core.DB {
- return engine.db
-}
-
-// Dialect return database dialect
-func (engine *Engine) Dialect() core.Dialect {
- return engine.dialect
-}
-
-// NewSession New a session
-func (engine *Engine) NewSession() *Session {
- session := &Session{engine: engine}
- session.Init()
- return session
-}
-
-// Close the engine
-func (engine *Engine) Close() error {
- return engine.db.Close()
-}
-
-// Ping tests if database is alive
-func (engine *Engine) Ping() error {
- session := engine.NewSession()
- defer session.Close()
- return session.Ping()
-}
-
-// logging sql
-func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
- if engine.showSQL && !engine.showExecTime {
- if len(sqlArgs) > 0 {
- engine.logger.Infof("[SQL] %v %#v", sqlStr, sqlArgs)
- } else {
- engine.logger.Infof("[SQL] %v", sqlStr)
- }
- }
-}
-
-// Sql provides raw sql input parameter. When you have a complex SQL statement
-// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
-//
-// Deprecated: use SQL instead.
-func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
- return engine.SQL(querystring, args...)
-}
-
-// SQL method let's you manually write raw SQL and operate
-// For example:
-//
-// engine.SQL("select * from user").Find(&users)
-//
-// This code will execute "select * from user" and set the records to users
-func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.SQL(query, args...)
-}
-
-// NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields
-// will automatically be filled with current time when Insert or Update
-// invoked. Call NoAutoTime if you dont' want to fill automatically.
-func (engine *Engine) NoAutoTime() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.NoAutoTime()
-}
-
-// NoAutoCondition disable auto generate Where condition from bean or not
-func (engine *Engine) NoAutoCondition(no ...bool) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.NoAutoCondition(no...)
-}
-
-// DBMetas Retrieve all tables, columns, indexes' informations from database.
-func (engine *Engine) DBMetas() ([]*core.Table, error) {
- tables, err := engine.dialect.GetTables()
- if err != nil {
- return nil, err
- }
-
- for _, table := range tables {
- colSeq, cols, err := engine.dialect.GetColumns(table.Name)
- if err != nil {
- return nil, err
- }
- for _, name := range colSeq {
- table.AddColumn(cols[name])
- }
- indexes, err := engine.dialect.GetIndexes(table.Name)
- if err != nil {
- return nil, err
- }
- table.Indexes = indexes
-
- for _, index := range indexes {
- for _, name := range index.Cols {
- if col := table.GetColumn(name); col != nil {
- col.Indexes[index.Name] = index.Type
- } else {
- return nil, fmt.Errorf("Unknown col %s in index %v of table %v, columns %v", name, index.Name, table.Name, table.ColumnsSeq())
- }
- }
- }
- }
- return tables, nil
-}
-
-// DumpAllToFile dump database all table structs and data to a file
-func (engine *Engine) DumpAllToFile(fp string, tp ...core.DbType) error {
- f, err := os.Create(fp)
- if err != nil {
- return err
- }
- defer f.Close()
- return engine.DumpAll(f, tp...)
-}
-
-// DumpAll dump database all table structs and data to w
-func (engine *Engine) DumpAll(w io.Writer, tp ...core.DbType) error {
- tables, err := engine.DBMetas()
- if err != nil {
- return err
- }
- return engine.DumpTables(tables, w, tp...)
-}
-
-// DumpTablesToFile dump specified tables to SQL file.
-func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error {
- f, err := os.Create(fp)
- if err != nil {
- return err
- }
- defer f.Close()
- return engine.DumpTables(tables, f, tp...)
-}
-
-// DumpTables dump specify tables to io.Writer
-func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
- return engine.dumpTables(tables, w, tp...)
-}
-
-// dumpTables dump database all table structs and data to w with specify db type
-func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
- var dialect core.Dialect
- var distDBName string
- if len(tp) == 0 {
- dialect = engine.dialect
- distDBName = string(engine.dialect.DBType())
- } else {
- dialect = core.QueryDialect(tp[0])
- if dialect == nil {
- return errors.New("Unsupported database type")
- }
- dialect.Init(nil, engine.dialect.URI(), "", "")
- distDBName = string(tp[0])
- }
-
- _, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm v%s %s, from %s to %s*/\n\n",
- Version, time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"), engine.dialect.DBType(), strings.ToUpper(distDBName)))
- if err != nil {
- return err
- }
-
- for i, table := range tables {
- if i > 0 {
- _, err = io.WriteString(w, "\n")
- if err != nil {
- return err
- }
- }
- _, err = io.WriteString(w, dialect.CreateTableSql(table, "", table.StoreEngine, "")+";\n")
- if err != nil {
- return err
- }
- for _, index := range table.Indexes {
- _, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n")
- if err != nil {
- return err
- }
- }
-
- cols := table.ColumnsSeq()
- colNames := engine.dialect.Quote(strings.Join(cols, engine.dialect.Quote(", ")))
- destColNames := dialect.Quote(strings.Join(cols, dialect.Quote(", ")))
-
- rows, err := engine.DB().Query("SELECT " + colNames + " FROM " + engine.Quote(table.Name))
- if err != nil {
- return err
- }
- defer rows.Close()
-
- for rows.Next() {
- dest := make([]interface{}, len(cols))
- err = rows.ScanSlice(&dest)
- if err != nil {
- return err
- }
-
- _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+destColNames+") VALUES (")
- if err != nil {
- return err
- }
-
- var temp string
- for i, d := range dest {
- col := table.GetColumn(cols[i])
- if col == nil {
- return errors.New("unknow column error")
- }
-
- if d == nil {
- temp += ", NULL"
- } else if col.SQLType.IsText() || col.SQLType.IsTime() {
- var v = fmt.Sprintf("%s", d)
- if strings.HasSuffix(v, " +0000 UTC") {
- temp += fmt.Sprintf(", '%s'", v[0:len(v)-len(" +0000 UTC")])
- } else {
- temp += ", '" + strings.Replace(v, "'", "''", -1) + "'"
- }
- } else if col.SQLType.IsBlob() {
- if reflect.TypeOf(d).Kind() == reflect.Slice {
- temp += fmt.Sprintf(", %s", dialect.FormatBytes(d.([]byte)))
- } else if reflect.TypeOf(d).Kind() == reflect.String {
- temp += fmt.Sprintf(", '%s'", d.(string))
- }
- } else if col.SQLType.IsNumeric() {
- switch reflect.TypeOf(d).Kind() {
- case reflect.Slice:
- if col.SQLType.Name == core.Bool {
- temp += fmt.Sprintf(", %v", strconv.FormatBool(d.([]byte)[0] != byte('0')))
- } else {
- temp += fmt.Sprintf(", %s", string(d.([]byte)))
- }
- case reflect.Int16, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
- if col.SQLType.Name == core.Bool {
- temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Int() > 0))
- } else {
- temp += fmt.Sprintf(", %v", d)
- }
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- if col.SQLType.Name == core.Bool {
- temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Uint() > 0))
- } else {
- temp += fmt.Sprintf(", %v", d)
- }
- default:
- temp += fmt.Sprintf(", %v", d)
- }
- } else {
- s := fmt.Sprintf("%v", d)
- if strings.Contains(s, ":") || strings.Contains(s, "-") {
- if strings.HasSuffix(s, " +0000 UTC") {
- temp += fmt.Sprintf(", '%s'", s[0:len(s)-len(" +0000 UTC")])
- } else {
- temp += fmt.Sprintf(", '%s'", s)
- }
- } else {
- temp += fmt.Sprintf(", %s", s)
- }
- }
- }
- _, err = io.WriteString(w, temp[2:]+");\n")
- if err != nil {
- return err
- }
- }
-
- // FIXME: Hack for postgres
- if string(dialect.DBType()) == core.POSTGRES && table.AutoIncrColumn() != nil {
- _, err = io.WriteString(w, "SELECT setval('"+table.Name+"_id_seq', COALESCE((SELECT MAX("+table.AutoIncrColumn().Name+") + 1 FROM "+dialect.Quote(table.Name)+"), 1), false);\n")
- if err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// Cascade use cascade or not
-func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Cascade(trueOrFalse...)
-}
-
-// Where method provide a condition query
-func (engine *Engine) Where(query interface{}, args ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Where(query, args...)
-}
-
-// Id will be deprecated, please use ID instead
-func (engine *Engine) Id(id interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Id(id)
-}
-
-// ID method provoide a condition as (id) = ?
-func (engine *Engine) ID(id interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.ID(id)
-}
-
-// Before apply before Processor, affected bean is passed to closure arg
-func (engine *Engine) Before(closures func(interface{})) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Before(closures)
-}
-
-// After apply after insert Processor, affected bean is passed to closure arg
-func (engine *Engine) After(closures func(interface{})) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.After(closures)
-}
-
-// Charset set charset when create table, only support mysql now
-func (engine *Engine) Charset(charset string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Charset(charset)
-}
-
-// StoreEngine set store engine when create table, only support mysql now
-func (engine *Engine) StoreEngine(storeEngine string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.StoreEngine(storeEngine)
-}
-
-// Distinct use for distinct columns. Caution: when you are using cache,
-// distinct will not be cached because cache system need id,
-// but distinct will not provide id
-func (engine *Engine) Distinct(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Distinct(columns...)
-}
-
-// Select customerize your select columns or contents
-func (engine *Engine) Select(str string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Select(str)
-}
-
-// Cols only use the parameters as select or update columns
-func (engine *Engine) Cols(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Cols(columns...)
-}
-
-// AllCols indicates that all columns should be use
-func (engine *Engine) AllCols() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.AllCols()
-}
-
-// MustCols specify some columns must use even if they are empty
-func (engine *Engine) MustCols(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.MustCols(columns...)
-}
-
-// UseBool xorm automatically retrieve condition according struct, but
-// if struct has bool field, it will ignore them. So use UseBool
-// to tell system to do not ignore them.
-// If no parameters, it will use all the bool field of struct, or
-// it will use parameters's columns
-func (engine *Engine) UseBool(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.UseBool(columns...)
-}
-
-// Omit only not use the parameters as select or update columns
-func (engine *Engine) Omit(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Omit(columns...)
-}
-
-// Nullable set null when column is zero-value and nullable for update
-func (engine *Engine) Nullable(columns ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Nullable(columns...)
-}
-
-// In will generate "column IN (?, ?)"
-func (engine *Engine) In(column string, args ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.In(column, args...)
-}
-
-// NotIn will generate "column NOT IN (?, ?)"
-func (engine *Engine) NotIn(column string, args ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.NotIn(column, args...)
-}
-
-// Incr provides a update string like "column = column + ?"
-func (engine *Engine) Incr(column string, arg ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Incr(column, arg...)
-}
-
-// Decr provides a update string like "column = column - ?"
-func (engine *Engine) Decr(column string, arg ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Decr(column, arg...)
-}
-
-// SetExpr provides a update string like "column = {expression}"
-func (engine *Engine) SetExpr(column string, expression string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.SetExpr(column, expression)
-}
-
-// Table temporarily change the Get, Find, Update's table
-func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Table(tableNameOrBean)
-}
-
-// Alias set the table alias
-func (engine *Engine) Alias(alias string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Alias(alias)
-}
-
-// Limit will generate "LIMIT start, limit"
-func (engine *Engine) Limit(limit int, start ...int) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Limit(limit, start...)
-}
-
-// Desc will generate "ORDER BY column1 DESC, column2 DESC"
-func (engine *Engine) Desc(colNames ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Desc(colNames...)
-}
-
-// Asc will generate "ORDER BY column1,column2 Asc"
-// This method can chainable use.
-//
-// engine.Desc("name").Asc("age").Find(&users)
-// // SELECT * FROM user ORDER BY name DESC, age ASC
-//
-func (engine *Engine) Asc(colNames ...string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Asc(colNames...)
-}
-
-// OrderBy will generate "ORDER BY order"
-func (engine *Engine) OrderBy(order string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.OrderBy(order)
-}
-
-// Prepare enables prepare statement
-func (engine *Engine) Prepare() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Prepare()
-}
-
-// Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
-func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Join(joinOperator, tablename, condition, args...)
-}
-
-// GroupBy generate group by statement
-func (engine *Engine) GroupBy(keys string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.GroupBy(keys)
-}
-
-// Having generate having statement
-func (engine *Engine) Having(conditions string) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Having(conditions)
-}
-
-// UnMapType removes the datbase mapper of a type
-func (engine *Engine) UnMapType(t reflect.Type) {
- engine.mutex.Lock()
- defer engine.mutex.Unlock()
- delete(engine.Tables, t)
-}
-
-func (engine *Engine) autoMapType(v reflect.Value) (*core.Table, error) {
- t := v.Type()
- engine.mutex.Lock()
- defer engine.mutex.Unlock()
- table, ok := engine.Tables[t]
- if !ok {
- var err error
- table, err = engine.mapType(v)
- if err != nil {
- return nil, err
- }
-
- engine.Tables[t] = table
- if engine.Cacher != nil {
- if v.CanAddr() {
- engine.GobRegister(v.Addr().Interface())
- } else {
- engine.GobRegister(v.Interface())
- }
- }
- }
- return table, nil
-}
-
-// GobRegister register one struct to gob for cache use
-func (engine *Engine) GobRegister(v interface{}) *Engine {
- gob.Register(v)
- return engine
-}
-
-// Table table struct
-type Table struct {
- *core.Table
- Name string
-}
-
-// IsValid if table is valid
-func (t *Table) IsValid() bool {
- return t.Table != nil && len(t.Name) > 0
-}
-
-// TableInfo get table info according to bean's content
-func (engine *Engine) TableInfo(bean interface{}) *Table {
- v := rValue(bean)
- tb, err := engine.autoMapType(v)
- if err != nil {
- engine.logger.Error(err)
- }
- return &Table{tb, engine.TableName(bean)}
-}
-
-func addIndex(indexName string, table *core.Table, col *core.Column, indexType int) {
- if index, ok := table.Indexes[indexName]; ok {
- index.AddColumn(col.Name)
- col.Indexes[index.Name] = indexType
- } else {
- index := core.NewIndex(indexName, indexType)
- index.AddColumn(col.Name)
- table.AddIndex(index)
- col.Indexes[index.Name] = indexType
- }
-}
-
-// TableName table name interface to define customerize table name
-type TableName interface {
- TableName() string
-}
-
-var (
- tpTableName = reflect.TypeOf((*TableName)(nil)).Elem()
-)
-
-func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
- t := v.Type()
- table := core.NewEmptyTable()
- table.Type = t
- table.Name = engine.tbNameForMap(v)
-
- var idFieldColName string
- var hasCacheTag, hasNoCacheTag bool
-
- for i := 0; i < t.NumField(); i++ {
- tag := t.Field(i).Tag
-
- ormTagStr := tag.Get(engine.TagIdentifier)
- var col *core.Column
- fieldValue := v.Field(i)
- fieldType := fieldValue.Type()
-
- if ormTagStr != "" {
- col = &core.Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
- IsAutoIncrement: false, MapType: core.TWOSIDES, Indexes: make(map[string]int)}
- tags := splitTag(ormTagStr)
-
- if len(tags) > 0 {
- if tags[0] == "-" {
- continue
- }
-
- var ctx = tagContext{
- table: table,
- col: col,
- fieldValue: fieldValue,
- indexNames: make(map[string]int),
- engine: engine,
- }
-
- if strings.HasPrefix(strings.ToUpper(tags[0]), "EXTENDS") {
- pStart := strings.Index(tags[0], "(")
- if pStart > -1 && strings.HasSuffix(tags[0], ")") {
- var tagPrefix = strings.TrimFunc(tags[0][pStart+1:len(tags[0])-1], func(r rune) bool {
- return r == '\'' || r == '"'
- })
-
- ctx.params = []string{tagPrefix}
- }
-
- if err := ExtendsTagHandler(&ctx); err != nil {
- return nil, err
- }
- continue
- }
-
- for j, key := range tags {
- if ctx.ignoreNext {
- ctx.ignoreNext = false
- continue
- }
-
- k := strings.ToUpper(key)
- ctx.tagName = k
- ctx.params = []string{}
-
- pStart := strings.Index(k, "(")
- if pStart == 0 {
- return nil, errors.New("( could not be the first charactor")
- }
- if pStart > -1 {
- if !strings.HasSuffix(k, ")") {
- return nil, fmt.Errorf("field %s tag %s cannot match ) charactor", col.FieldName, key)
- }
-
- ctx.tagName = k[:pStart]
- ctx.params = strings.Split(key[pStart+1:len(k)-1], ",")
- }
-
- if j > 0 {
- ctx.preTag = strings.ToUpper(tags[j-1])
- }
- if j < len(tags)-1 {
- ctx.nextTag = tags[j+1]
- } else {
- ctx.nextTag = ""
- }
-
- if h, ok := engine.tagHandlers[ctx.tagName]; ok {
- if err := h(&ctx); err != nil {
- return nil, err
- }
- } else {
- if strings.HasPrefix(key, "'") && strings.HasSuffix(key, "'") {
- col.Name = key[1 : len(key)-1]
- } else {
- col.Name = key
- }
- }
-
- if ctx.hasCacheTag {
- hasCacheTag = true
- }
- if ctx.hasNoCacheTag {
- hasNoCacheTag = true
- }
- }
-
- if col.SQLType.Name == "" {
- col.SQLType = core.Type2SQLType(fieldType)
- }
- engine.dialect.SqlType(col)
- if col.Length == 0 {
- col.Length = col.SQLType.DefaultLength
- }
- if col.Length2 == 0 {
- col.Length2 = col.SQLType.DefaultLength2
- }
- if col.Name == "" {
- col.Name = engine.ColumnMapper.Obj2Table(t.Field(i).Name)
- }
-
- if ctx.isUnique {
- ctx.indexNames[col.Name] = core.UniqueType
- } else if ctx.isIndex {
- ctx.indexNames[col.Name] = core.IndexType
- }
-
- for indexName, indexType := range ctx.indexNames {
- addIndex(indexName, table, col, indexType)
- }
- }
- } else {
- var sqlType core.SQLType
- if fieldValue.CanAddr() {
- if _, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
- sqlType = core.SQLType{Name: core.Text}
- }
- }
- if _, ok := fieldValue.Interface().(core.Conversion); ok {
- sqlType = core.SQLType{Name: core.Text}
- } else {
- sqlType = core.Type2SQLType(fieldType)
- }
- col = core.NewColumn(engine.ColumnMapper.Obj2Table(t.Field(i).Name),
- t.Field(i).Name, sqlType, sqlType.DefaultLength,
- sqlType.DefaultLength2, true)
-
- if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) {
- idFieldColName = col.Name
- }
- }
- if col.IsAutoIncrement {
- col.Nullable = false
- }
-
- table.AddColumn(col)
-
- } // end for
-
- if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
- col := table.GetColumn(idFieldColName)
- col.IsPrimaryKey = true
- col.IsAutoIncrement = true
- col.Nullable = false
- table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
- table.AutoIncrement = col.Name
- }
-
- if hasCacheTag {
- if engine.Cacher != nil { // !nash! use engine's cacher if provided
- engine.logger.Info("enable cache on table:", table.Name)
- engine.setCacher(table.Name, engine.Cacher)
- } else {
- engine.logger.Info("enable LRU cache on table:", table.Name)
- engine.setCacher(table.Name, NewLRUCacher2(NewMemoryStore(), time.Hour, 10000))
- }
- }
- if hasNoCacheTag {
- engine.logger.Info("disable cache on table:", table.Name)
- engine.setCacher(table.Name, nil)
- }
-
- return table, nil
-}
-
-// IsTableEmpty if a table has any reocrd
-func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.IsTableEmpty(bean)
-}
-
-// IsTableExist if a table is exist
-func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.IsTableExist(beanOrTableName)
-}
-
-// IdOf get id from one struct
-//
-// Deprecated: use IDOf instead.
-func (engine *Engine) IdOf(bean interface{}) core.PK {
- return engine.IDOf(bean)
-}
-
-// IDOf get id from one struct
-func (engine *Engine) IDOf(bean interface{}) core.PK {
- return engine.IdOfV(reflect.ValueOf(bean))
-}
-
-// IdOfV get id from one value of struct
-//
-// Deprecated: use IDOfV instead.
-func (engine *Engine) IdOfV(rv reflect.Value) core.PK {
- return engine.IDOfV(rv)
-}
-
-// IDOfV get id from one value of struct
-func (engine *Engine) IDOfV(rv reflect.Value) core.PK {
- pk, err := engine.idOfV(rv)
- if err != nil {
- engine.logger.Error(err)
- return nil
- }
- return pk
-}
-
-func (engine *Engine) idOfV(rv reflect.Value) (core.PK, error) {
- v := reflect.Indirect(rv)
- table, err := engine.autoMapType(v)
- if err != nil {
- return nil, err
- }
-
- pk := make([]interface{}, len(table.PrimaryKeys))
- for i, col := range table.PKColumns() {
- var err error
-
- fieldName := col.FieldName
- for {
- parts := strings.SplitN(fieldName, ".", 2)
- if len(parts) == 1 {
- break
- }
-
- v = v.FieldByName(parts[0])
- if v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- if v.Kind() != reflect.Struct {
- return nil, ErrUnSupportedType
- }
- fieldName = parts[1]
- }
-
- pkField := v.FieldByName(fieldName)
- switch pkField.Kind() {
- case reflect.String:
- pk[i], err = engine.idTypeAssertion(col, pkField.String())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- pk[i], err = engine.idTypeAssertion(col, strconv.FormatInt(pkField.Int(), 10))
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- // id of uint will be converted to int64
- pk[i], err = engine.idTypeAssertion(col, strconv.FormatUint(pkField.Uint(), 10))
- }
-
- if err != nil {
- return nil, err
- }
- }
- return core.PK(pk), nil
-}
-
-func (engine *Engine) idTypeAssertion(col *core.Column, sid string) (interface{}, error) {
- if col.SQLType.IsNumeric() {
- n, err := strconv.ParseInt(sid, 10, 64)
- if err != nil {
- return nil, err
- }
- return n, nil
- } else if col.SQLType.IsText() {
- return sid, nil
- } else {
- return nil, errors.New("not supported")
- }
-}
-
-// CreateIndexes create indexes
-func (engine *Engine) CreateIndexes(bean interface{}) error {
- session := engine.NewSession()
- defer session.Close()
- return session.CreateIndexes(bean)
-}
-
-// CreateUniques create uniques
-func (engine *Engine) CreateUniques(bean interface{}) error {
- session := engine.NewSession()
- defer session.Close()
- return session.CreateUniques(bean)
-}
-
-// ClearCacheBean if enabled cache, clear the cache bean
-func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
- tableName := engine.TableName(bean)
- cacher := engine.getCacher(tableName)
- if cacher != nil {
- cacher.ClearIds(tableName)
- cacher.DelBean(tableName, id)
- }
- return nil
-}
-
-// ClearCache if enabled cache, clear some tables' cache
-func (engine *Engine) ClearCache(beans ...interface{}) error {
- for _, bean := range beans {
- tableName := engine.TableName(bean)
- cacher := engine.getCacher(tableName)
- if cacher != nil {
- cacher.ClearIds(tableName)
- cacher.ClearBeans(tableName)
- }
- }
- return nil
-}
-
-// Sync the new struct changes to database, this method will automatically add
-// table, column, index, unique. but will not delete or change anything.
-// If you change some field, you should change the database manually.
-func (engine *Engine) Sync(beans ...interface{}) error {
- session := engine.NewSession()
- defer session.Close()
-
- for _, bean := range beans {
- v := rValue(bean)
- tableNameNoSchema := engine.TableName(bean)
- table, err := engine.autoMapType(v)
- if err != nil {
- return err
- }
-
- isExist, err := session.Table(bean).isTableExist(tableNameNoSchema)
- if err != nil {
- return err
- }
- if !isExist {
- err = session.createTable(bean)
- if err != nil {
- return err
- }
- }
- /*isEmpty, err := engine.IsEmptyTable(bean)
- if err != nil {
- return err
- }*/
- var isEmpty bool
- if isEmpty {
- err = session.dropTable(bean)
- if err != nil {
- return err
- }
- err = session.createTable(bean)
- if err != nil {
- return err
- }
- } else {
- for _, col := range table.Columns() {
- isExist, err := engine.dialect.IsColumnExist(tableNameNoSchema, col.Name)
- if err != nil {
- return err
- }
- if !isExist {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
- err = session.addColumn(col.Name)
- if err != nil {
- return err
- }
- }
- }
-
- for name, index := range table.Indexes {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
- if index.Type == core.UniqueType {
- isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, true)
- if err != nil {
- return err
- }
- if !isExist {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- err = session.addUnique(tableNameNoSchema, name)
- if err != nil {
- return err
- }
- }
- } else if index.Type == core.IndexType {
- isExist, err := session.isIndexExist2(tableNameNoSchema, index.Cols, false)
- if err != nil {
- return err
- }
- if !isExist {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- err = session.addIndex(tableNameNoSchema, name)
- if err != nil {
- return err
- }
- }
- } else {
- return errors.New("unknow index type")
- }
- }
- }
- }
- return nil
-}
-
-// Sync2 synchronize structs to database tables
-func (engine *Engine) Sync2(beans ...interface{}) error {
- s := engine.NewSession()
- defer s.Close()
- return s.Sync2(beans...)
-}
-
-// CreateTables create tabls according bean
-func (engine *Engine) CreateTables(beans ...interface{}) error {
- session := engine.NewSession()
- defer session.Close()
-
- err := session.Begin()
- if err != nil {
- return err
- }
-
- for _, bean := range beans {
- err = session.createTable(bean)
- if err != nil {
- session.Rollback()
- return err
- }
- }
- return session.Commit()
-}
-
-// DropTables drop specify tables
-func (engine *Engine) DropTables(beans ...interface{}) error {
- session := engine.NewSession()
- defer session.Close()
-
- err := session.Begin()
- if err != nil {
- return err
- }
-
- for _, bean := range beans {
- err = session.dropTable(bean)
- if err != nil {
- session.Rollback()
- return err
- }
- }
- return session.Commit()
-}
-
-// DropIndexes drop indexes of a table
-func (engine *Engine) DropIndexes(bean interface{}) error {
- session := engine.NewSession()
- defer session.Close()
- return session.DropIndexes(bean)
-}
-
-// Exec raw sql
-func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Exec(sqlOrArgs...)
-}
-
-// Query a raw sql and return records as []map[string][]byte
-func (engine *Engine) Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Query(sqlOrArgs...)
-}
-
-// QueryString runs a raw sql and return records as []map[string]string
-func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.QueryString(sqlOrArgs...)
-}
-
-// QueryInterface runs a raw sql and return records as []map[string]interface{}
-func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.QueryInterface(sqlOrArgs...)
-}
-
-// Insert one or more records
-func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Insert(beans...)
-}
-
-// InsertOne insert only one record
-func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.InsertOne(bean)
-}
-
-// Update records, bean's non-empty fields are updated contents,
-// condiBean' non-empty filds are conditions
-// CAUTION:
-// 1.bool will defaultly be updated content nor conditions
-// You should call UseBool if you have bool to use.
-// 2.float32 & float64 may be not inexact as conditions
-func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Update(bean, condiBeans...)
-}
-
-// Delete records, bean's non-empty fields are conditions
-func (engine *Engine) Delete(bean interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Delete(bean)
-}
-
-// Get retrieve one record from table, bean's non-empty fields
-// are conditions
-func (engine *Engine) Get(bean interface{}) (bool, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Get(bean)
-}
-
-// Exist returns true if the record exist otherwise return false
-func (engine *Engine) Exist(bean ...interface{}) (bool, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Exist(bean...)
-}
-
-// Find retrieve records from table, condiBeans's non-empty fields
-// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
-// map[int64]*Struct
-func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
- session := engine.NewSession()
- defer session.Close()
- return session.Find(beans, condiBeans...)
-}
-
-// FindAndCount find the results and also return the counts
-func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.FindAndCount(rowsSlicePtr, condiBean...)
-}
-
-// Iterate record by record handle records from table, bean's non-empty fields
-// are conditions.
-func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
- session := engine.NewSession()
- defer session.Close()
- return session.Iterate(bean, fun)
-}
-
-// Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
-// are conditions.
-func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
- session := engine.NewSession()
- return session.Rows(bean)
-}
-
-// Count counts the records. bean's non-empty fields are conditions.
-func (engine *Engine) Count(bean ...interface{}) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Count(bean...)
-}
-
-// Sum sum the records by some column. bean's non-empty fields are conditions.
-func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Sum(bean, colName)
-}
-
-// SumInt sum the records by some column. bean's non-empty fields are conditions.
-func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.SumInt(bean, colName)
-}
-
-// Sums sum the records by some columns. bean's non-empty fields are conditions.
-func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.Sums(bean, colNames...)
-}
-
-// SumsInt like Sums but return slice of int64 instead of float64.
-func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
- session := engine.NewSession()
- defer session.Close()
- return session.SumsInt(bean, colNames...)
-}
-
-// ImportFile SQL DDL file
-func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
- file, err := os.Open(ddlPath)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- return engine.Import(file)
-}
-
-// Import SQL DDL from io.Reader
-func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
- var results []sql.Result
- var lastError error
- scanner := bufio.NewScanner(r)
-
- semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
- if atEOF && len(data) == 0 {
- return 0, nil, nil
- }
- if i := bytes.IndexByte(data, ';'); i >= 0 {
- return i + 1, data[0:i], nil
- }
- // If we're at EOF, we have a final, non-terminated line. Return it.
- if atEOF {
- return len(data), data, nil
- }
- // Request more data.
- return 0, nil, nil
- }
-
- scanner.Split(semiColSpliter)
-
- for scanner.Scan() {
- query := strings.Trim(scanner.Text(), " \t\n\r")
- if len(query) > 0 {
- engine.logSQL(query)
- result, err := engine.DB().Exec(query)
- results = append(results, result)
- if err != nil {
- return nil, err
- }
- }
- }
-
- return results, lastError
-}
-
-// nowTime return current time
-func (engine *Engine) nowTime(col *core.Column) (interface{}, time.Time) {
- t := time.Now()
- var tz = engine.DatabaseTZ
- if !col.DisableTimeZone && col.TimeZone != nil {
- tz = col.TimeZone
- }
- return engine.formatTime(col.SQLType.Name, t.In(tz)), t.In(engine.TZLocation)
-}
-
-func (engine *Engine) formatColTime(col *core.Column, t time.Time) (v interface{}) {
- if t.IsZero() {
- if col.Nullable {
- return nil
- }
- return ""
- }
-
- if col.TimeZone != nil {
- return engine.formatTime(col.SQLType.Name, t.In(col.TimeZone))
- }
- return engine.formatTime(col.SQLType.Name, t.In(engine.DatabaseTZ))
-}
-
-// formatTime format time as column type
-func (engine *Engine) formatTime(sqlTypeName string, t time.Time) (v interface{}) {
- switch sqlTypeName {
- case core.Time:
- s := t.Format("2006-01-02 15:04:05") //time.RFC3339
- v = s[11:19]
- case core.Date:
- v = t.Format("2006-01-02")
- case core.DateTime, core.TimeStamp:
- v = t.Format("2006-01-02 15:04:05")
- case core.TimeStampz:
- if engine.dialect.DBType() == core.MSSQL {
- v = t.Format("2006-01-02T15:04:05.9999999Z07:00")
- } else {
- v = t.Format(time.RFC3339Nano)
- }
- case core.BigInt, core.Int:
- v = t.Unix()
- default:
- v = t
- }
- return
-}
-
-// GetColumnMapper returns the column name mapper
-func (engine *Engine) GetColumnMapper() core.IMapper {
- return engine.ColumnMapper
-}
-
-// GetTableMapper returns the table name mapper
-func (engine *Engine) GetTableMapper() core.IMapper {
- return engine.TableMapper
-}
-
-// GetTZLocation returns time zone of the application
-func (engine *Engine) GetTZLocation() *time.Location {
- return engine.TZLocation
-}
-
-// SetTZLocation sets time zone of the application
-func (engine *Engine) SetTZLocation(tz *time.Location) {
- engine.TZLocation = tz
-}
-
-// GetTZDatabase returns time zone of the database
-func (engine *Engine) GetTZDatabase() *time.Location {
- return engine.DatabaseTZ
-}
-
-// SetTZDatabase sets time zone of the database
-func (engine *Engine) SetTZDatabase(tz *time.Location) {
- engine.DatabaseTZ = tz
-}
-
-// SetSchema sets the schema of database
-func (engine *Engine) SetSchema(schema string) {
- engine.dialect.URI().Schema = schema
-}
-
-// Unscoped always disable struct tag "deleted"
-func (engine *Engine) Unscoped() *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Unscoped()
-}
diff --git a/vendor/github.com/go-xorm/xorm/engine_cond.go b/vendor/github.com/go-xorm/xorm/engine_cond.go
deleted file mode 100644
index 702ac80..0000000
--- a/vendor/github.com/go-xorm/xorm/engine_cond.go
+++ /dev/null
@@ -1,232 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql/driver"
- "fmt"
- "reflect"
- "strings"
- "time"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-func (engine *Engine) buildConds(table *core.Table, bean interface{},
- includeVersion bool, includeUpdated bool, includeNil bool,
- includeAutoIncr bool, allUseBool bool, useAllCols bool, unscoped bool,
- mustColumnMap map[string]bool, tableName, aliasName string, addedTableName bool) (builder.Cond, error) {
- var conds []builder.Cond
- for _, col := range table.Columns() {
- if !includeVersion && col.IsVersion {
- continue
- }
- if !includeUpdated && col.IsUpdated {
- continue
- }
- if !includeAutoIncr && col.IsAutoIncrement {
- continue
- }
-
- if engine.dialect.DBType() == core.MSSQL && (col.SQLType.Name == core.Text || col.SQLType.IsBlob() || col.SQLType.Name == core.TimeStampz) {
- continue
- }
- if col.SQLType.IsJson() {
- continue
- }
-
- var colName string
- if addedTableName {
- var nm = tableName
- if len(aliasName) > 0 {
- nm = aliasName
- }
- colName = engine.Quote(nm) + "." + engine.Quote(col.Name)
- } else {
- colName = engine.Quote(col.Name)
- }
-
- fieldValuePtr, err := col.ValueOf(bean)
- if err != nil {
- if !strings.Contains(err.Error(), "is not valid") {
- engine.logger.Warn(err)
- }
- continue
- }
-
- if col.IsDeleted && !unscoped { // tag "deleted" is enabled
- conds = append(conds, engine.CondDeleted(colName))
- }
-
- fieldValue := *fieldValuePtr
- if fieldValue.Interface() == nil {
- continue
- }
-
- fieldType := reflect.TypeOf(fieldValue.Interface())
- requiredField := useAllCols
-
- if b, ok := getFlagForColumn(mustColumnMap, col); ok {
- if b {
- requiredField = true
- } else {
- continue
- }
- }
-
- if fieldType.Kind() == reflect.Ptr {
- if fieldValue.IsNil() {
- if includeNil {
- conds = append(conds, builder.Eq{colName: nil})
- }
- continue
- } else if !fieldValue.IsValid() {
- continue
- } else {
- // dereference ptr type to instance type
- fieldValue = fieldValue.Elem()
- fieldType = reflect.TypeOf(fieldValue.Interface())
- requiredField = true
- }
- }
-
- var val interface{}
- switch fieldType.Kind() {
- case reflect.Bool:
- if allUseBool || requiredField {
- val = fieldValue.Interface()
- } else {
- // if a bool in a struct, it will not be as a condition because it default is false,
- // please use Where() instead
- continue
- }
- case reflect.String:
- if !requiredField && fieldValue.String() == "" {
- continue
- }
- // for MyString, should convert to string or panic
- if fieldType.String() != reflect.String.String() {
- val = fieldValue.String()
- } else {
- val = fieldValue.Interface()
- }
- case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64:
- if !requiredField && fieldValue.Int() == 0 {
- continue
- }
- val = fieldValue.Interface()
- case reflect.Float32, reflect.Float64:
- if !requiredField && fieldValue.Float() == 0.0 {
- continue
- }
- val = fieldValue.Interface()
- case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
- if !requiredField && fieldValue.Uint() == 0 {
- continue
- }
- t := int64(fieldValue.Uint())
- val = reflect.ValueOf(&t).Interface()
- case reflect.Struct:
- if fieldType.ConvertibleTo(core.TimeType) {
- t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
- if !requiredField && (t.IsZero() || !fieldValue.IsValid()) {
- continue
- }
- val = engine.formatColTime(col, t)
- } else if _, ok := reflect.New(fieldType).Interface().(core.Conversion); ok {
- continue
- } else if valNul, ok := fieldValue.Interface().(driver.Valuer); ok {
- val, _ = valNul.Value()
- if val == nil {
- continue
- }
- } else {
- if col.SQLType.IsJson() {
- if col.SQLType.IsText() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = string(bytes)
- } else if col.SQLType.IsBlob() {
- var bytes []byte
- var err error
- bytes, err = DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = bytes
- }
- } else {
- engine.autoMapType(fieldValue)
- if table, ok := engine.Tables[fieldValue.Type()]; ok {
- if len(table.PrimaryKeys) == 1 {
- pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
- // fix non-int pk issues
- //if pkField.Int() != 0 {
- if pkField.IsValid() && !isZero(pkField.Interface()) {
- val = pkField.Interface()
- } else {
- continue
- }
- } else {
- //TODO: how to handler?
- return nil, fmt.Errorf("not supported %v as %v", fieldValue.Interface(), table.PrimaryKeys)
- }
- } else {
- val = fieldValue.Interface()
- }
- }
- }
- case reflect.Array:
- continue
- case reflect.Slice, reflect.Map:
- if fieldValue == reflect.Zero(fieldType) {
- continue
- }
- if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 {
- continue
- }
-
- if col.SQLType.IsText() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = string(bytes)
- } else if col.SQLType.IsBlob() {
- var bytes []byte
- var err error
- if (fieldType.Kind() == reflect.Array || fieldType.Kind() == reflect.Slice) &&
- fieldType.Elem().Kind() == reflect.Uint8 {
- if fieldValue.Len() > 0 {
- val = fieldValue.Bytes()
- } else {
- continue
- }
- } else {
- bytes, err = DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = bytes
- }
- } else {
- continue
- }
- default:
- val = fieldValue.Interface()
- }
-
- conds = append(conds, builder.Eq{colName: val})
- }
-
- return builder.And(conds...), nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/engine_context.go b/vendor/github.com/go-xorm/xorm/engine_context.go
deleted file mode 100644
index c6cbb76..0000000
--- a/vendor/github.com/go-xorm/xorm/engine_context.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2019 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build go1.8
-
-package xorm
-
-import "context"
-
-// Context creates a session with the context
-func (engine *Engine) Context(ctx context.Context) *Session {
- session := engine.NewSession()
- session.isAutoClose = true
- return session.Context(ctx)
-}
-
-// SetDefaultContext set the default context
-func (engine *Engine) SetDefaultContext(ctx context.Context) {
- engine.defaultContext = ctx
-}
-
-// PingContext tests if database is alive
-func (engine *Engine) PingContext(ctx context.Context) error {
- session := engine.NewSession()
- defer session.Close()
- return session.PingContext(ctx)
-}
diff --git a/vendor/github.com/go-xorm/xorm/engine_group.go b/vendor/github.com/go-xorm/xorm/engine_group.go
deleted file mode 100644
index 42d49ec..0000000
--- a/vendor/github.com/go-xorm/xorm/engine_group.go
+++ /dev/null
@@ -1,219 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "context"
- "time"
-
- "xorm.io/core"
-)
-
-// EngineGroup defines an engine group
-type EngineGroup struct {
- *Engine
- slaves []*Engine
- policy GroupPolicy
-}
-
-// NewEngineGroup creates a new engine group
-func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error) {
- var eg EngineGroup
- if len(policies) > 0 {
- eg.policy = policies[0]
- } else {
- eg.policy = RoundRobinPolicy()
- }
-
- driverName, ok1 := args1.(string)
- conns, ok2 := args2.([]string)
- if ok1 && ok2 {
- engines := make([]*Engine, len(conns))
- for i, conn := range conns {
- engine, err := NewEngine(driverName, conn)
- if err != nil {
- return nil, err
- }
- engine.engineGroup = &eg
- engines[i] = engine
- }
-
- eg.Engine = engines[0]
- eg.slaves = engines[1:]
- return &eg, nil
- }
-
- master, ok3 := args1.(*Engine)
- slaves, ok4 := args2.([]*Engine)
- if ok3 && ok4 {
- master.engineGroup = &eg
- for i := 0; i < len(slaves); i++ {
- slaves[i].engineGroup = &eg
- }
- eg.Engine = master
- eg.slaves = slaves
- return &eg, nil
- }
- return nil, ErrParamsType
-}
-
-// Close the engine
-func (eg *EngineGroup) Close() error {
- err := eg.Engine.Close()
- if err != nil {
- return err
- }
-
- for i := 0; i < len(eg.slaves); i++ {
- err := eg.slaves[i].Close()
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// Context returned a group session
-func (eg *EngineGroup) Context(ctx context.Context) *Session {
- sess := eg.NewSession()
- sess.isAutoClose = true
- return sess.Context(ctx)
-}
-
-// NewSession returned a group session
-func (eg *EngineGroup) NewSession() *Session {
- sess := eg.Engine.NewSession()
- sess.sessionType = groupSession
- return sess
-}
-
-// Master returns the master engine
-func (eg *EngineGroup) Master() *Engine {
- return eg.Engine
-}
-
-// Ping tests if database is alive
-func (eg *EngineGroup) Ping() error {
- if err := eg.Engine.Ping(); err != nil {
- return err
- }
-
- for _, slave := range eg.slaves {
- if err := slave.Ping(); err != nil {
- return err
- }
- }
- return nil
-}
-
-// SetColumnMapper set the column name mapping rule
-func (eg *EngineGroup) SetColumnMapper(mapper core.IMapper) {
- eg.Engine.ColumnMapper = mapper
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].ColumnMapper = mapper
- }
-}
-
-// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
-func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration) {
- eg.Engine.SetConnMaxLifetime(d)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].SetConnMaxLifetime(d)
- }
-}
-
-// SetDefaultCacher set the default cacher
-func (eg *EngineGroup) SetDefaultCacher(cacher core.Cacher) {
- eg.Engine.SetDefaultCacher(cacher)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].SetDefaultCacher(cacher)
- }
-}
-
-// SetLogger set the new logger
-func (eg *EngineGroup) SetLogger(logger core.ILogger) {
- eg.Engine.SetLogger(logger)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].SetLogger(logger)
- }
-}
-
-// SetLogLevel sets the logger level
-func (eg *EngineGroup) SetLogLevel(level core.LogLevel) {
- eg.Engine.SetLogLevel(level)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].SetLogLevel(level)
- }
-}
-
-// SetMapper set the name mapping rules
-func (eg *EngineGroup) SetMapper(mapper core.IMapper) {
- eg.Engine.SetMapper(mapper)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].SetMapper(mapper)
- }
-}
-
-// SetMaxIdleConns set the max idle connections on pool, default is 2
-func (eg *EngineGroup) SetMaxIdleConns(conns int) {
- eg.Engine.db.SetMaxIdleConns(conns)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].db.SetMaxIdleConns(conns)
- }
-}
-
-// SetMaxOpenConns is only available for go 1.2+
-func (eg *EngineGroup) SetMaxOpenConns(conns int) {
- eg.Engine.db.SetMaxOpenConns(conns)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].db.SetMaxOpenConns(conns)
- }
-}
-
-// SetPolicy set the group policy
-func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup {
- eg.policy = policy
- return eg
-}
-
-// SetTableMapper set the table name mapping rule
-func (eg *EngineGroup) SetTableMapper(mapper core.IMapper) {
- eg.Engine.TableMapper = mapper
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].TableMapper = mapper
- }
-}
-
-// ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO
-func (eg *EngineGroup) ShowExecTime(show ...bool) {
- eg.Engine.ShowExecTime(show...)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].ShowExecTime(show...)
- }
-}
-
-// ShowSQL show SQL statement or not on logger if log level is great than INFO
-func (eg *EngineGroup) ShowSQL(show ...bool) {
- eg.Engine.ShowSQL(show...)
- for i := 0; i < len(eg.slaves); i++ {
- eg.slaves[i].ShowSQL(show...)
- }
-}
-
-// Slave returns one of the physical databases which is a slave according the policy
-func (eg *EngineGroup) Slave() *Engine {
- switch len(eg.slaves) {
- case 0:
- return eg.Engine
- case 1:
- return eg.slaves[0]
- }
- return eg.policy.Slave(eg)
-}
-
-// Slaves returns all the slaves
-func (eg *EngineGroup) Slaves() []*Engine {
- return eg.slaves
-}
diff --git a/vendor/github.com/go-xorm/xorm/engine_group_policy.go b/vendor/github.com/go-xorm/xorm/engine_group_policy.go
deleted file mode 100644
index 5b56e89..0000000
--- a/vendor/github.com/go-xorm/xorm/engine_group_policy.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "math/rand"
- "sync"
- "time"
-)
-
-// GroupPolicy is be used by chosing the current slave from slaves
-type GroupPolicy interface {
- Slave(*EngineGroup) *Engine
-}
-
-// GroupPolicyHandler should be used when a function is a GroupPolicy
-type GroupPolicyHandler func(*EngineGroup) *Engine
-
-// Slave implements the chosen of slaves
-func (h GroupPolicyHandler) Slave(eg *EngineGroup) *Engine {
- return h(eg)
-}
-
-// RandomPolicy implmentes randomly chose the slave of slaves
-func RandomPolicy() GroupPolicyHandler {
- var r = rand.New(rand.NewSource(time.Now().UnixNano()))
- return func(g *EngineGroup) *Engine {
- return g.Slaves()[r.Intn(len(g.Slaves()))]
- }
-}
-
-// WeightRandomPolicy implmentes randomly chose the slave of slaves
-func WeightRandomPolicy(weights []int) GroupPolicyHandler {
- var rands = make([]int, 0, len(weights))
- for i := 0; i < len(weights); i++ {
- for n := 0; n < weights[i]; n++ {
- rands = append(rands, i)
- }
- }
- var r = rand.New(rand.NewSource(time.Now().UnixNano()))
-
- return func(g *EngineGroup) *Engine {
- var slaves = g.Slaves()
- idx := rands[r.Intn(len(rands))]
- if idx >= len(slaves) {
- idx = len(slaves) - 1
- }
- return slaves[idx]
- }
-}
-
-func RoundRobinPolicy() GroupPolicyHandler {
- var pos = -1
- var lock sync.Mutex
- return func(g *EngineGroup) *Engine {
- var slaves = g.Slaves()
-
- lock.Lock()
- defer lock.Unlock()
- pos++
- if pos >= len(slaves) {
- pos = 0
- }
-
- return slaves[pos]
- }
-}
-
-func WeightRoundRobinPolicy(weights []int) GroupPolicyHandler {
- var rands = make([]int, 0, len(weights))
- for i := 0; i < len(weights); i++ {
- for n := 0; n < weights[i]; n++ {
- rands = append(rands, i)
- }
- }
- var pos = -1
- var lock sync.Mutex
-
- return func(g *EngineGroup) *Engine {
- var slaves = g.Slaves()
- lock.Lock()
- defer lock.Unlock()
- pos++
- if pos >= len(rands) {
- pos = 0
- }
-
- idx := rands[pos]
- if idx >= len(slaves) {
- idx = len(slaves) - 1
- }
- return slaves[idx]
- }
-}
-
-// LeastConnPolicy implements GroupPolicy, every time will get the least connections slave
-func LeastConnPolicy() GroupPolicyHandler {
- return func(g *EngineGroup) *Engine {
- var slaves = g.Slaves()
- connections := 0
- idx := 0
- for i := 0; i < len(slaves); i++ {
- openConnections := slaves[i].DB().Stats().OpenConnections
- if i == 0 {
- connections = openConnections
- idx = i
- } else if openConnections <= connections {
- connections = openConnections
- idx = i
- }
- }
- return slaves[idx]
- }
-}
diff --git a/vendor/github.com/go-xorm/xorm/engine_table.go b/vendor/github.com/go-xorm/xorm/engine_table.go
deleted file mode 100644
index eb5aa85..0000000
--- a/vendor/github.com/go-xorm/xorm/engine_table.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2018 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "xorm.io/core"
-)
-
-// tbNameWithSchema will automatically add schema prefix on table name
-func (engine *Engine) tbNameWithSchema(v string) string {
- // Add schema name as prefix of table name.
- // Only for postgres database.
- if engine.dialect.DBType() == core.POSTGRES &&
- engine.dialect.URI().Schema != "" &&
- engine.dialect.URI().Schema != postgresPublicSchema &&
- strings.Index(v, ".") == -1 {
- return engine.dialect.URI().Schema + "." + v
- }
- return v
-}
-
-// TableName returns table name with schema prefix if has
-func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string {
- tbName := engine.tbNameNoSchema(bean)
- if len(includeSchema) > 0 && includeSchema[0] {
- tbName = engine.tbNameWithSchema(tbName)
- }
-
- return tbName
-}
-
-// tbName get some table's table name
-func (session *Session) tbNameNoSchema(table *core.Table) string {
- if len(session.statement.AltTableName) > 0 {
- return session.statement.AltTableName
- }
-
- return table.Name
-}
-
-func (engine *Engine) tbNameForMap(v reflect.Value) string {
- if v.Type().Implements(tpTableName) {
- return v.Interface().(TableName).TableName()
- }
- if v.Kind() == reflect.Ptr {
- v = v.Elem()
- if v.Type().Implements(tpTableName) {
- return v.Interface().(TableName).TableName()
- }
- }
-
- return engine.TableMapper.Obj2Table(v.Type().Name())
-}
-
-func (engine *Engine) tbNameNoSchema(tablename interface{}) string {
- switch tablename.(type) {
- case []string:
- t := tablename.([]string)
- if len(t) > 1 {
- return fmt.Sprintf("%v AS %v", engine.Quote(t[0]), engine.Quote(t[1]))
- } else if len(t) == 1 {
- return engine.Quote(t[0])
- }
- case []interface{}:
- t := tablename.([]interface{})
- l := len(t)
- var table string
- if l > 0 {
- f := t[0]
- switch f.(type) {
- case string:
- table = f.(string)
- case TableName:
- table = f.(TableName).TableName()
- default:
- v := rValue(f)
- t := v.Type()
- if t.Kind() == reflect.Struct {
- table = engine.tbNameForMap(v)
- } else {
- table = engine.Quote(fmt.Sprintf("%v", f))
- }
- }
- }
- if l > 1 {
- return fmt.Sprintf("%v AS %v", engine.Quote(table),
- engine.Quote(fmt.Sprintf("%v", t[1])))
- } else if l == 1 {
- return engine.Quote(table)
- }
- case TableName:
- return tablename.(TableName).TableName()
- case string:
- return tablename.(string)
- case reflect.Value:
- v := tablename.(reflect.Value)
- return engine.tbNameForMap(v)
- default:
- v := rValue(tablename)
- t := v.Type()
- if t.Kind() == reflect.Struct {
- return engine.tbNameForMap(v)
- }
- return engine.Quote(fmt.Sprintf("%v", tablename))
- }
- return ""
-}
diff --git a/vendor/github.com/go-xorm/xorm/error.go b/vendor/github.com/go-xorm/xorm/error.go
deleted file mode 100644
index a67527a..0000000
--- a/vendor/github.com/go-xorm/xorm/error.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
-)
-
-var (
- // ErrParamsType params error
- ErrParamsType = errors.New("Params type error")
- // ErrTableNotFound table not found error
- ErrTableNotFound = errors.New("Table not found")
- // ErrUnSupportedType unsupported error
- ErrUnSupportedType = errors.New("Unsupported type error")
- // ErrNotExist record does not exist error
- ErrNotExist = errors.New("Record does not exist")
- // ErrCacheFailed cache failed error
- ErrCacheFailed = errors.New("Cache failed")
- // ErrNeedDeletedCond delete needs less one condition error
- ErrNeedDeletedCond = errors.New("Delete action needs at least one condition")
- // ErrNotImplemented not implemented
- ErrNotImplemented = errors.New("Not implemented")
- // ErrConditionType condition type unsupported
- ErrConditionType = errors.New("Unsupported condition type")
- // ErrUnSupportedSQLType parameter of SQL is not supported
- ErrUnSupportedSQLType = errors.New("unsupported sql type")
-)
-
-// ErrFieldIsNotExist columns does not exist
-type ErrFieldIsNotExist struct {
- FieldName string
- TableName string
-}
-
-func (e ErrFieldIsNotExist) Error() string {
- return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
-}
-
-// ErrFieldIsNotValid is not valid
-type ErrFieldIsNotValid struct {
- FieldName string
- TableName string
-}
-
-func (e ErrFieldIsNotValid) Error() string {
- return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
-}
diff --git a/vendor/github.com/go-xorm/xorm/gen_reserved.sh b/vendor/github.com/go-xorm/xorm/gen_reserved.sh
deleted file mode 100644
index 434a1bf..0000000
--- a/vendor/github.com/go-xorm/xorm/gen_reserved.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/bash
-if [ -f $1 ];then
- cat $1| awk '{printf("\""$1"\":true,\n")}'
-else
- echo "argument $1 if not a file!"
-fi
diff --git a/vendor/github.com/go-xorm/xorm/go.mod b/vendor/github.com/go-xorm/xorm/go.mod
deleted file mode 100644
index 4f53390..0000000
--- a/vendor/github.com/go-xorm/xorm/go.mod
+++ /dev/null
@@ -1,19 +0,0 @@
-module github.com/go-xorm/xorm
-
-require (
- github.com/cockroachdb/apd v1.1.0 // indirect
- github.com/denisenkom/go-mssqldb v0.0.0-20190707035753-2be1aa521ff4
- github.com/go-sql-driver/mysql v1.4.1
- github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 // indirect
- github.com/jackc/pgx v3.3.0+incompatible
- github.com/kr/pretty v0.1.0 // indirect
- github.com/lib/pq v1.0.0
- github.com/mattn/go-sqlite3 v1.10.0
- github.com/pkg/errors v0.8.1 // indirect
- github.com/satori/go.uuid v1.2.0 // indirect
- github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24 // indirect
- github.com/stretchr/testify v1.3.0
- github.com/ziutek/mymysql v1.5.4
- xorm.io/builder v0.3.5
- xorm.io/core v0.6.3
-)
diff --git a/vendor/github.com/go-xorm/xorm/go.sum b/vendor/github.com/go-xorm/xorm/go.sum
deleted file mode 100644
index f00ff97..0000000
--- a/vendor/github.com/go-xorm/xorm/go.sum
+++ /dev/null
@@ -1,159 +0,0 @@
-cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg=
-cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU=
-cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
-github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
-github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
-github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
-github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
-github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
-github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
-github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
-github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
-github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
-github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
-github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/denisenkom/go-mssqldb v0.0.0-20190707035753-2be1aa521ff4 h1:YcpmyvADGYw5LqMnHqSkyIELsHCGF6PkrmM31V8rF7o=
-github.com/denisenkom/go-mssqldb v0.0.0-20190707035753-2be1aa521ff4/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM=
-github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
-github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
-github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I=
-github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
-github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
-github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
-github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
-github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
-github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
-github.com/go-xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:9wScpmSP5A3Bk8V3XHWUcJmYTh+ZnlHVyc+A4oZYS3Y=
-github.com/go-xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:56xuuqnHyryaerycW3BfssRdxQstACi0Epw/yC5E2xM=
-github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
-github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
-github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
-github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
-github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
-github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
-github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
-github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
-github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
-github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
-github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
-github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
-github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
-github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
-github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
-github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
-github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 h1:vr3AYkKovP8uR8AvSGGUK1IDqRa5lAAvEkZG1LKaCRc=
-github.com/jackc/fake v0.0.0-20150926172116-812a484cc733/go.mod h1:WrMFNQdiFJ80sQsxDoMokWK1W5TQtxBFNpzWTD84ibQ=
-github.com/jackc/pgx v3.3.0+incompatible h1:Wa90/+qsITBAPkAZjiByeIGHFcj3Ztu+VzrrIpHjL90=
-github.com/jackc/pgx v3.3.0+incompatible/go.mod h1:0ZGrqGqkRlliWnWB4zKnWtjbSWbGkVEFm4TeybAXq+I=
-github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
-github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
-github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
-github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
-github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
-github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
-github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
-github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
-github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
-github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
-github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
-github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
-github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o=
-github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
-github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
-github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
-github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
-github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
-github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
-github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
-github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
-github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
-github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
-github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs=
-github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
-github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
-github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
-github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
-github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
-github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
-github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
-github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
-github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24 h1:pntxY8Ary0t43dCZ5dqY4YTJCObLY1kIXl0uzMv+7DE=
-github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
-github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
-github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
-github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs=
-github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0=
-go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
-golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI=
-golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
-golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
-golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
-golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
-golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
-golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
-golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
-golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
-golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
-golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
-google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk=
-google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
-google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
-google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
-google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
-google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
-google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
-google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
-google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
-gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
-gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
-gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
-gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-xorm.io/builder v0.3.5 h1:EilU39fvWDxjb1cDaELpYhsF+zziRBhew8xk4pngO+A=
-xorm.io/builder v0.3.5/go.mod h1:ZFbByS/KxZI1FKRjL05PyJ4YrK2bcxlUaAxdum5aTR8=
-xorm.io/core v0.6.3 h1:n1NhVZt1s2oLw1BZfX2ocIJsHyso259uPgg63BGr37M=
-xorm.io/core v0.6.3/go.mod h1:8kz/C6arVW/O9vk3PgCiMJO2hIAm1UcuOL3dSPyZ2qo=
diff --git a/vendor/github.com/go-xorm/xorm/helpers.go b/vendor/github.com/go-xorm/xorm/helpers.go
deleted file mode 100644
index db8fc58..0000000
--- a/vendor/github.com/go-xorm/xorm/helpers.go
+++ /dev/null
@@ -1,311 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "strings"
-
- "xorm.io/core"
-)
-
-// str2PK convert string value to primary key value according to tp
-func str2PKValue(s string, tp reflect.Type) (reflect.Value, error) {
- var err error
- var result interface{}
- var defReturn = reflect.Zero(tp)
-
- switch tp.Kind() {
- case reflect.Int:
- result, err = strconv.Atoi(s)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as int: %s", s, err.Error())
- }
- case reflect.Int8:
- x, err := strconv.Atoi(s)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as int8: %s", s, err.Error())
- }
- result = int8(x)
- case reflect.Int16:
- x, err := strconv.Atoi(s)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as int16: %s", s, err.Error())
- }
- result = int16(x)
- case reflect.Int32:
- x, err := strconv.Atoi(s)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as int32: %s", s, err.Error())
- }
- result = int32(x)
- case reflect.Int64:
- result, err = strconv.ParseInt(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as int64: %s", s, err.Error())
- }
- case reflect.Uint:
- x, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as uint: %s", s, err.Error())
- }
- result = uint(x)
- case reflect.Uint8:
- x, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as uint8: %s", s, err.Error())
- }
- result = uint8(x)
- case reflect.Uint16:
- x, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as uint16: %s", s, err.Error())
- }
- result = uint16(x)
- case reflect.Uint32:
- x, err := strconv.ParseUint(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as uint32: %s", s, err.Error())
- }
- result = uint32(x)
- case reflect.Uint64:
- result, err = strconv.ParseUint(s, 10, 64)
- if err != nil {
- return defReturn, fmt.Errorf("convert %s as uint64: %s", s, err.Error())
- }
- case reflect.String:
- result = s
- default:
- return defReturn, errors.New("unsupported convert type")
- }
- return reflect.ValueOf(result).Convert(tp), nil
-}
-
-func str2PK(s string, tp reflect.Type) (interface{}, error) {
- v, err := str2PKValue(s, tp)
- if err != nil {
- return nil, err
- }
- return v.Interface(), nil
-}
-
-func splitTag(tag string) (tags []string) {
- tag = strings.TrimSpace(tag)
- var hasQuote = false
- var lastIdx = 0
- for i, t := range tag {
- if t == '\'' {
- hasQuote = !hasQuote
- } else if t == ' ' {
- if lastIdx < i && !hasQuote {
- tags = append(tags, strings.TrimSpace(tag[lastIdx:i]))
- lastIdx = i + 1
- }
- }
- }
- if lastIdx < len(tag) {
- tags = append(tags, strings.TrimSpace(tag[lastIdx:]))
- }
- return
-}
-
-type zeroable interface {
- IsZero() bool
-}
-
-func isZero(k interface{}) bool {
- switch k.(type) {
- case int:
- return k.(int) == 0
- case int8:
- return k.(int8) == 0
- case int16:
- return k.(int16) == 0
- case int32:
- return k.(int32) == 0
- case int64:
- return k.(int64) == 0
- case uint:
- return k.(uint) == 0
- case uint8:
- return k.(uint8) == 0
- case uint16:
- return k.(uint16) == 0
- case uint32:
- return k.(uint32) == 0
- case uint64:
- return k.(uint64) == 0
- case float32:
- return k.(float32) == 0
- case float64:
- return k.(float64) == 0
- case bool:
- return k.(bool) == false
- case string:
- return k.(string) == ""
- case zeroable:
- return k.(zeroable).IsZero()
- }
- return false
-}
-
-func isStructZero(v reflect.Value) bool {
- if !v.IsValid() {
- return true
- }
-
- for i := 0; i < v.NumField(); i++ {
- field := v.Field(i)
- switch field.Kind() {
- case reflect.Ptr:
- field = field.Elem()
- fallthrough
- case reflect.Struct:
- if !isStructZero(field) {
- return false
- }
- default:
- if field.CanInterface() && !isZero(field.Interface()) {
- return false
- }
- }
- }
- return true
-}
-
-func isArrayValueZero(v reflect.Value) bool {
- if !v.IsValid() || v.Len() == 0 {
- return true
- }
-
- for i := 0; i < v.Len(); i++ {
- if !isZero(v.Index(i).Interface()) {
- return false
- }
- }
-
- return true
-}
-
-func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
- var v interface{}
- kind := tp.Kind()
-
- if kind == reflect.Ptr {
- kind = tp.Elem().Kind()
- }
-
- switch kind {
- case reflect.Int16:
- temp := int16(id)
- v = &temp
- case reflect.Int32:
- temp := int32(id)
- v = &temp
- case reflect.Int:
- temp := int(id)
- v = &temp
- case reflect.Int64:
- temp := id
- v = &temp
- case reflect.Uint16:
- temp := uint16(id)
- v = &temp
- case reflect.Uint32:
- temp := uint32(id)
- v = &temp
- case reflect.Uint64:
- temp := uint64(id)
- v = &temp
- case reflect.Uint:
- temp := uint(id)
- v = &temp
- }
-
- if tp.Kind() == reflect.Ptr {
- return reflect.ValueOf(v).Convert(tp)
- }
- return reflect.ValueOf(v).Elem().Convert(tp)
-}
-
-func int64ToInt(id int64, tp reflect.Type) interface{} {
- return int64ToIntValue(id, tp).Interface()
-}
-
-func isPKZero(pk core.PK) bool {
- for _, k := range pk {
- if isZero(k) {
- return true
- }
- }
- return false
-}
-
-func indexNoCase(s, sep string) int {
- return strings.Index(strings.ToLower(s), strings.ToLower(sep))
-}
-
-func splitNoCase(s, sep string) []string {
- idx := indexNoCase(s, sep)
- if idx < 0 {
- return []string{s}
- }
- return strings.Split(s, s[idx:idx+len(sep)])
-}
-
-func splitNNoCase(s, sep string, n int) []string {
- idx := indexNoCase(s, sep)
- if idx < 0 {
- return []string{s}
- }
- return strings.SplitN(s, s[idx:idx+len(sep)], n)
-}
-
-func makeArray(elem string, count int) []string {
- res := make([]string, count)
- for i := 0; i < count; i++ {
- res[i] = elem
- }
- return res
-}
-
-func rValue(bean interface{}) reflect.Value {
- return reflect.Indirect(reflect.ValueOf(bean))
-}
-
-func rType(bean interface{}) reflect.Type {
- sliceValue := reflect.Indirect(reflect.ValueOf(bean))
- //return reflect.TypeOf(sliceValue.Interface())
- return sliceValue.Type()
-}
-
-func structName(v reflect.Type) string {
- for v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- return v.Name()
-}
-
-func sliceEq(left, right []string) bool {
- if len(left) != len(right) {
- return false
- }
- sort.Sort(sort.StringSlice(left))
- sort.Sort(sort.StringSlice(right))
- for i := 0; i < len(left); i++ {
- if left[i] != right[i] {
- return false
- }
- }
- return true
-}
-
-func indexName(tableName, idxName string) string {
- return fmt.Sprintf("IDX_%v_%v", tableName, idxName)
-}
diff --git a/vendor/github.com/go-xorm/xorm/helpler_time.go b/vendor/github.com/go-xorm/xorm/helpler_time.go
deleted file mode 100644
index f4013e2..0000000
--- a/vendor/github.com/go-xorm/xorm/helpler_time.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import "time"
-
-const (
- zeroTime0 = "0000-00-00 00:00:00"
- zeroTime1 = "0001-01-01 00:00:00"
-)
-
-func formatTime(t time.Time) string {
- return t.Format("2006-01-02 15:04:05")
-}
-
-func isTimeZero(t time.Time) bool {
- return t.IsZero() || formatTime(t) == zeroTime0 ||
- formatTime(t) == zeroTime1
-}
diff --git a/vendor/github.com/go-xorm/xorm/interface.go b/vendor/github.com/go-xorm/xorm/interface.go
deleted file mode 100644
index 0928f66..0000000
--- a/vendor/github.com/go-xorm/xorm/interface.go
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "context"
- "database/sql"
- "reflect"
- "time"
-
- "xorm.io/core"
-)
-
-// Interface defines the interface which Engine, EngineGroup and Session will implementate.
-type Interface interface {
- AllCols() *Session
- Alias(alias string) *Session
- Asc(colNames ...string) *Session
- BufferSize(size int) *Session
- Cols(columns ...string) *Session
- Count(...interface{}) (int64, error)
- CreateIndexes(bean interface{}) error
- CreateUniques(bean interface{}) error
- Decr(column string, arg ...interface{}) *Session
- Desc(...string) *Session
- Delete(interface{}) (int64, error)
- Distinct(columns ...string) *Session
- DropIndexes(bean interface{}) error
- Exec(sqlOrArgs ...interface{}) (sql.Result, error)
- Exist(bean ...interface{}) (bool, error)
- Find(interface{}, ...interface{}) error
- FindAndCount(interface{}, ...interface{}) (int64, error)
- Get(interface{}) (bool, error)
- GroupBy(keys string) *Session
- ID(interface{}) *Session
- In(string, ...interface{}) *Session
- Incr(column string, arg ...interface{}) *Session
- Insert(...interface{}) (int64, error)
- InsertOne(interface{}) (int64, error)
- IsTableEmpty(bean interface{}) (bool, error)
- IsTableExist(beanOrTableName interface{}) (bool, error)
- Iterate(interface{}, IterFunc) error
- Limit(int, ...int) *Session
- MustCols(columns ...string) *Session
- NoAutoCondition(...bool) *Session
- NotIn(string, ...interface{}) *Session
- Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session
- Omit(columns ...string) *Session
- OrderBy(order string) *Session
- Ping() error
- Query(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
- QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- Rows(bean interface{}) (*Rows, error)
- SetExpr(string, string) *Session
- SQL(interface{}, ...interface{}) *Session
- Sum(bean interface{}, colName string) (float64, error)
- SumInt(bean interface{}, colName string) (int64, error)
- Sums(bean interface{}, colNames ...string) ([]float64, error)
- SumsInt(bean interface{}, colNames ...string) ([]int64, error)
- Table(tableNameOrBean interface{}) *Session
- Unscoped() *Session
- Update(bean interface{}, condiBeans ...interface{}) (int64, error)
- UseBool(...string) *Session
- Where(interface{}, ...interface{}) *Session
-}
-
-// EngineInterface defines the interface which Engine, EngineGroup will implementate.
-type EngineInterface interface {
- Interface
-
- Before(func(interface{})) *Session
- Charset(charset string) *Session
- ClearCache(...interface{}) error
- Context(context.Context) *Session
- CreateTables(...interface{}) error
- DBMetas() ([]*core.Table, error)
- Dialect() core.Dialect
- DropTables(...interface{}) error
- DumpAllToFile(fp string, tp ...core.DbType) error
- GetCacher(string) core.Cacher
- GetColumnMapper() core.IMapper
- GetDefaultCacher() core.Cacher
- GetTableMapper() core.IMapper
- GetTZDatabase() *time.Location
- GetTZLocation() *time.Location
- MapCacher(interface{}, core.Cacher) error
- NewSession() *Session
- NoAutoTime() *Session
- Quote(string) string
- SetCacher(string, core.Cacher)
- SetConnMaxLifetime(time.Duration)
- SetDefaultCacher(core.Cacher)
- SetLogger(logger core.ILogger)
- SetLogLevel(core.LogLevel)
- SetMapper(core.IMapper)
- SetMaxOpenConns(int)
- SetMaxIdleConns(int)
- SetSchema(string)
- SetTZDatabase(tz *time.Location)
- SetTZLocation(tz *time.Location)
- ShowExecTime(...bool)
- ShowSQL(show ...bool)
- Sync(...interface{}) error
- Sync2(...interface{}) error
- StoreEngine(storeEngine string) *Session
- TableInfo(bean interface{}) *Table
- TableName(interface{}, ...bool) string
- UnMapType(reflect.Type)
-}
-
-var (
- _ Interface = &Session{}
- _ EngineInterface = &Engine{}
- _ EngineInterface = &EngineGroup{}
-)
diff --git a/vendor/github.com/go-xorm/xorm/json.go b/vendor/github.com/go-xorm/xorm/json.go
deleted file mode 100644
index fdb6ce5..0000000
--- a/vendor/github.com/go-xorm/xorm/json.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2019 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import "encoding/json"
-
-// JSONInterface represents an interface to handle json data
-type JSONInterface interface {
- Marshal(v interface{}) ([]byte, error)
- Unmarshal(data []byte, v interface{}) error
-}
-
-var (
- // DefaultJSONHandler default json handler
- DefaultJSONHandler JSONInterface = StdJSON{}
-)
-
-// StdJSON implements JSONInterface via encoding/json
-type StdJSON struct{}
-
-// Marshal implements JSONInterface
-func (StdJSON) Marshal(v interface{}) ([]byte, error) {
- return json.Marshal(v)
-}
-
-// Unmarshal implements JSONInterface
-func (StdJSON) Unmarshal(data []byte, v interface{}) error {
- return json.Unmarshal(data, v)
-}
diff --git a/vendor/github.com/go-xorm/xorm/logger.go b/vendor/github.com/go-xorm/xorm/logger.go
deleted file mode 100644
index 7b26e77..0000000
--- a/vendor/github.com/go-xorm/xorm/logger.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "fmt"
- "io"
- "log"
-
- "xorm.io/core"
-)
-
-// default log options
-const (
- DEFAULT_LOG_PREFIX = "[xorm]"
- DEFAULT_LOG_FLAG = log.Ldate | log.Lmicroseconds
- DEFAULT_LOG_LEVEL = core.LOG_DEBUG
-)
-
-var _ core.ILogger = DiscardLogger{}
-
-// DiscardLogger don't log implementation for core.ILogger
-type DiscardLogger struct{}
-
-// Debug empty implementation
-func (DiscardLogger) Debug(v ...interface{}) {}
-
-// Debugf empty implementation
-func (DiscardLogger) Debugf(format string, v ...interface{}) {}
-
-// Error empty implementation
-func (DiscardLogger) Error(v ...interface{}) {}
-
-// Errorf empty implementation
-func (DiscardLogger) Errorf(format string, v ...interface{}) {}
-
-// Info empty implementation
-func (DiscardLogger) Info(v ...interface{}) {}
-
-// Infof empty implementation
-func (DiscardLogger) Infof(format string, v ...interface{}) {}
-
-// Warn empty implementation
-func (DiscardLogger) Warn(v ...interface{}) {}
-
-// Warnf empty implementation
-func (DiscardLogger) Warnf(format string, v ...interface{}) {}
-
-// Level empty implementation
-func (DiscardLogger) Level() core.LogLevel {
- return core.LOG_UNKNOWN
-}
-
-// SetLevel empty implementation
-func (DiscardLogger) SetLevel(l core.LogLevel) {}
-
-// ShowSQL empty implementation
-func (DiscardLogger) ShowSQL(show ...bool) {}
-
-// IsShowSQL empty implementation
-func (DiscardLogger) IsShowSQL() bool {
- return false
-}
-
-// SimpleLogger is the default implment of core.ILogger
-type SimpleLogger struct {
- DEBUG *log.Logger
- ERR *log.Logger
- INFO *log.Logger
- WARN *log.Logger
- level core.LogLevel
- showSQL bool
-}
-
-var _ core.ILogger = &SimpleLogger{}
-
-// NewSimpleLogger use a special io.Writer as logger output
-func NewSimpleLogger(out io.Writer) *SimpleLogger {
- return NewSimpleLogger2(out, DEFAULT_LOG_PREFIX, DEFAULT_LOG_FLAG)
-}
-
-// NewSimpleLogger2 let you customrize your logger prefix and flag
-func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger {
- return NewSimpleLogger3(out, prefix, flag, DEFAULT_LOG_LEVEL)
-}
-
-// NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel
-func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger {
- return &SimpleLogger{
- DEBUG: log.New(out, fmt.Sprintf("%s [debug] ", prefix), flag),
- ERR: log.New(out, fmt.Sprintf("%s [error] ", prefix), flag),
- INFO: log.New(out, fmt.Sprintf("%s [info] ", prefix), flag),
- WARN: log.New(out, fmt.Sprintf("%s [warn] ", prefix), flag),
- level: l,
- }
-}
-
-// Error implement core.ILogger
-func (s *SimpleLogger) Error(v ...interface{}) {
- if s.level <= core.LOG_ERR {
- s.ERR.Output(2, fmt.Sprint(v...))
- }
- return
-}
-
-// Errorf implement core.ILogger
-func (s *SimpleLogger) Errorf(format string, v ...interface{}) {
- if s.level <= core.LOG_ERR {
- s.ERR.Output(2, fmt.Sprintf(format, v...))
- }
- return
-}
-
-// Debug implement core.ILogger
-func (s *SimpleLogger) Debug(v ...interface{}) {
- if s.level <= core.LOG_DEBUG {
- s.DEBUG.Output(2, fmt.Sprint(v...))
- }
- return
-}
-
-// Debugf implement core.ILogger
-func (s *SimpleLogger) Debugf(format string, v ...interface{}) {
- if s.level <= core.LOG_DEBUG {
- s.DEBUG.Output(2, fmt.Sprintf(format, v...))
- }
- return
-}
-
-// Info implement core.ILogger
-func (s *SimpleLogger) Info(v ...interface{}) {
- if s.level <= core.LOG_INFO {
- s.INFO.Output(2, fmt.Sprint(v...))
- }
- return
-}
-
-// Infof implement core.ILogger
-func (s *SimpleLogger) Infof(format string, v ...interface{}) {
- if s.level <= core.LOG_INFO {
- s.INFO.Output(2, fmt.Sprintf(format, v...))
- }
- return
-}
-
-// Warn implement core.ILogger
-func (s *SimpleLogger) Warn(v ...interface{}) {
- if s.level <= core.LOG_WARNING {
- s.WARN.Output(2, fmt.Sprint(v...))
- }
- return
-}
-
-// Warnf implement core.ILogger
-func (s *SimpleLogger) Warnf(format string, v ...interface{}) {
- if s.level <= core.LOG_WARNING {
- s.WARN.Output(2, fmt.Sprintf(format, v...))
- }
- return
-}
-
-// Level implement core.ILogger
-func (s *SimpleLogger) Level() core.LogLevel {
- return s.level
-}
-
-// SetLevel implement core.ILogger
-func (s *SimpleLogger) SetLevel(l core.LogLevel) {
- s.level = l
- return
-}
-
-// ShowSQL implement core.ILogger
-func (s *SimpleLogger) ShowSQL(show ...bool) {
- if len(show) == 0 {
- s.showSQL = true
- return
- }
- s.showSQL = show[0]
-}
-
-// IsShowSQL implement core.ILogger
-func (s *SimpleLogger) IsShowSQL() bool {
- return s.showSQL
-}
diff --git a/vendor/github.com/go-xorm/xorm/pg_reserved.txt b/vendor/github.com/go-xorm/xorm/pg_reserved.txt
deleted file mode 100644
index 720ed37..0000000
--- a/vendor/github.com/go-xorm/xorm/pg_reserved.txt
+++ /dev/null
@@ -1,746 +0,0 @@
-A non-reserved non-reserved
-ABORT non-reserved
-ABS reserved reserved
-ABSENT non-reserved non-reserved
-ABSOLUTE non-reserved non-reserved non-reserved reserved
-ACCESS non-reserved
-ACCORDING non-reserved non-reserved
-ACTION non-reserved non-reserved non-reserved reserved
-ADA non-reserved non-reserved non-reserved
-ADD non-reserved non-reserved non-reserved reserved
-ADMIN non-reserved non-reserved non-reserved
-AFTER non-reserved non-reserved non-reserved
-AGGREGATE non-reserved
-ALL reserved reserved reserved reserved
-ALLOCATE reserved reserved reserved
-ALSO non-reserved
-ALTER non-reserved reserved reserved reserved
-ALWAYS non-reserved non-reserved non-reserved
-ANALYSE reserved
-ANALYZE reserved
-AND reserved reserved reserved reserved
-ANY reserved reserved reserved reserved
-ARE reserved reserved reserved
-ARRAY reserved reserved reserved
-ARRAY_AGG reserved reserved
-ARRAY_MAX_CARDINALITY reserved
-AS reserved reserved reserved reserved
-ASC reserved non-reserved non-reserved reserved
-ASENSITIVE reserved reserved
-ASSERTION non-reserved non-reserved non-reserved reserved
-ASSIGNMENT non-reserved non-reserved non-reserved
-ASYMMETRIC reserved reserved reserved
-AT non-reserved reserved reserved reserved
-ATOMIC reserved reserved
-ATTRIBUTE non-reserved non-reserved non-reserved
-ATTRIBUTES non-reserved non-reserved
-AUTHORIZATION reserved (can be function or type) reserved reserved reserved
-AVG reserved reserved reserved
-BACKWARD non-reserved
-BASE64 non-reserved non-reserved
-BEFORE non-reserved non-reserved non-reserved
-BEGIN non-reserved reserved reserved reserved
-BEGIN_FRAME reserved
-BEGIN_PARTITION reserved
-BERNOULLI non-reserved non-reserved
-BETWEEN non-reserved (cannot be function or type) reserved reserved reserved
-BIGINT non-reserved (cannot be function or type) reserved reserved
-BINARY reserved (can be function or type) reserved reserved
-BIT non-reserved (cannot be function or type) reserved
-BIT_LENGTH reserved
-BLOB reserved reserved
-BLOCKED non-reserved non-reserved
-BOM non-reserved non-reserved
-BOOLEAN non-reserved (cannot be function or type) reserved reserved
-BOTH reserved reserved reserved reserved
-BREADTH non-reserved non-reserved
-BY non-reserved reserved reserved reserved
-C non-reserved non-reserved non-reserved
-CACHE non-reserved
-CALL reserved reserved
-CALLED non-reserved reserved reserved
-CARDINALITY reserved reserved
-CASCADE non-reserved non-reserved non-reserved reserved
-CASCADED non-reserved reserved reserved reserved
-CASE reserved reserved reserved reserved
-CAST reserved reserved reserved reserved
-CATALOG non-reserved non-reserved non-reserved reserved
-CATALOG_NAME non-reserved non-reserved non-reserved
-CEIL reserved reserved
-CEILING reserved reserved
-CHAIN non-reserved non-reserved non-reserved
-CHAR non-reserved (cannot be function or type) reserved reserved reserved
-CHARACTER non-reserved (cannot be function or type) reserved reserved reserved
-CHARACTERISTICS non-reserved non-reserved non-reserved
-CHARACTERS non-reserved non-reserved
-CHARACTER_LENGTH reserved reserved reserved
-CHARACTER_SET_CATALOG non-reserved non-reserved non-reserved
-CHARACTER_SET_NAME non-reserved non-reserved non-reserved
-CHARACTER_SET_SCHEMA non-reserved non-reserved non-reserved
-CHAR_LENGTH reserved reserved reserved
-CHECK reserved reserved reserved reserved
-CHECKPOINT non-reserved
-CLASS non-reserved
-CLASS_ORIGIN non-reserved non-reserved non-reserved
-CLOB reserved reserved
-CLOSE non-reserved reserved reserved reserved
-CLUSTER non-reserved
-COALESCE non-reserved (cannot be function or type) reserved reserved reserved
-COBOL non-reserved non-reserved non-reserved
-COLLATE reserved reserved reserved reserved
-COLLATION reserved (can be function or type) non-reserved non-reserved reserved
-COLLATION_CATALOG non-reserved non-reserved non-reserved
-COLLATION_NAME non-reserved non-reserved non-reserved
-COLLATION_SCHEMA non-reserved non-reserved non-reserved
-COLLECT reserved reserved
-COLUMN reserved reserved reserved reserved
-COLUMNS non-reserved non-reserved
-COLUMN_NAME non-reserved non-reserved non-reserved
-COMMAND_FUNCTION non-reserved non-reserved non-reserved
-COMMAND_FUNCTION_CODE non-reserved non-reserved
-COMMENT non-reserved
-COMMENTS non-reserved
-COMMIT non-reserved reserved reserved reserved
-COMMITTED non-reserved non-reserved non-reserved non-reserved
-CONCURRENTLY reserved (can be function or type)
-CONDITION reserved reserved
-CONDITION_NUMBER non-reserved non-reserved non-reserved
-CONFIGURATION non-reserved
-CONNECT reserved reserved reserved
-CONNECTION non-reserved non-reserved non-reserved reserved
-CONNECTION_NAME non-reserved non-reserved non-reserved
-CONSTRAINT reserved reserved reserved reserved
-CONSTRAINTS non-reserved non-reserved non-reserved reserved
-CONSTRAINT_CATALOG non-reserved non-reserved non-reserved
-CONSTRAINT_NAME non-reserved non-reserved non-reserved
-CONSTRAINT_SCHEMA non-reserved non-reserved non-reserved
-CONSTRUCTOR non-reserved non-reserved
-CONTAINS reserved non-reserved
-CONTENT non-reserved non-reserved non-reserved
-CONTINUE non-reserved non-reserved non-reserved reserved
-CONTROL non-reserved non-reserved
-CONVERSION non-reserved
-CONVERT reserved reserved reserved
-COPY non-reserved
-CORR reserved reserved
-CORRESPONDING reserved reserved reserved
-COST non-reserved
-COUNT reserved reserved reserved
-COVAR_POP reserved reserved
-COVAR_SAMP reserved reserved
-CREATE reserved reserved reserved reserved
-CROSS reserved (can be function or type) reserved reserved reserved
-CSV non-reserved
-CUBE reserved reserved
-CUME_DIST reserved reserved
-CURRENT non-reserved reserved reserved reserved
-CURRENT_CATALOG reserved reserved reserved
-CURRENT_DATE reserved reserved reserved reserved
-CURRENT_DEFAULT_TRANSFORM_GROUP reserved reserved
-CURRENT_PATH reserved reserved
-CURRENT_ROLE reserved reserved reserved
-CURRENT_ROW reserved
-CURRENT_SCHEMA reserved (can be function or type) reserved reserved
-CURRENT_TIME reserved reserved reserved reserved
-CURRENT_TIMESTAMP reserved reserved reserved reserved
-CURRENT_TRANSFORM_GROUP_FOR_TYPE reserved reserved
-CURRENT_USER reserved reserved reserved reserved
-CURSOR non-reserved reserved reserved reserved
-CURSOR_NAME non-reserved non-reserved non-reserved
-CYCLE non-reserved reserved reserved
-DATA non-reserved non-reserved non-reserved non-reserved
-DATABASE non-reserved
-DATALINK reserved reserved
-DATE reserved reserved reserved
-DATETIME_INTERVAL_CODE non-reserved non-reserved non-reserved
-DATETIME_INTERVAL_PRECISION non-reserved non-reserved non-reserved
-DAY non-reserved reserved reserved reserved
-DB non-reserved non-reserved
-DEALLOCATE non-reserved reserved reserved reserved
-DEC non-reserved (cannot be function or type) reserved reserved reserved
-DECIMAL non-reserved (cannot be function or type) reserved reserved reserved
-DECLARE non-reserved reserved reserved reserved
-DEFAULT reserved reserved reserved reserved
-DEFAULTS non-reserved non-reserved non-reserved
-DEFERRABLE reserved non-reserved non-reserved reserved
-DEFERRED non-reserved non-reserved non-reserved reserved
-DEFINED non-reserved non-reserved
-DEFINER non-reserved non-reserved non-reserved
-DEGREE non-reserved non-reserved
-DELETE non-reserved reserved reserved reserved
-DELIMITER non-reserved
-DELIMITERS non-reserved
-DENSE_RANK reserved reserved
-DEPTH non-reserved non-reserved
-DEREF reserved reserved
-DERIVED non-reserved non-reserved
-DESC reserved non-reserved non-reserved reserved
-DESCRIBE reserved reserved reserved
-DESCRIPTOR non-reserved non-reserved reserved
-DETERMINISTIC reserved reserved
-DIAGNOSTICS non-reserved non-reserved reserved
-DICTIONARY non-reserved
-DISABLE non-reserved
-DISCARD non-reserved
-DISCONNECT reserved reserved reserved
-DISPATCH non-reserved non-reserved
-DISTINCT reserved reserved reserved reserved
-DLNEWCOPY reserved reserved
-DLPREVIOUSCOPY reserved reserved
-DLURLCOMPLETE reserved reserved
-DLURLCOMPLETEONLY reserved reserved
-DLURLCOMPLETEWRITE reserved reserved
-DLURLPATH reserved reserved
-DLURLPATHONLY reserved reserved
-DLURLPATHWRITE reserved reserved
-DLURLSCHEME reserved reserved
-DLURLSERVER reserved reserved
-DLVALUE reserved reserved
-DO reserved
-DOCUMENT non-reserved non-reserved non-reserved
-DOMAIN non-reserved non-reserved non-reserved reserved
-DOUBLE non-reserved reserved reserved reserved
-DROP non-reserved reserved reserved reserved
-DYNAMIC reserved reserved
-DYNAMIC_FUNCTION non-reserved non-reserved non-reserved
-DYNAMIC_FUNCTION_CODE non-reserved non-reserved
-EACH non-reserved reserved reserved
-ELEMENT reserved reserved
-ELSE reserved reserved reserved reserved
-EMPTY non-reserved non-reserved
-ENABLE non-reserved
-ENCODING non-reserved non-reserved non-reserved
-ENCRYPTED non-reserved
-END reserved reserved reserved reserved
-END-EXEC reserved reserved reserved
-END_FRAME reserved
-END_PARTITION reserved
-ENFORCED non-reserved
-ENUM non-reserved
-EQUALS reserved non-reserved
-ESCAPE non-reserved reserved reserved reserved
-EVENT non-reserved
-EVERY reserved reserved
-EXCEPT reserved reserved reserved reserved
-EXCEPTION reserved
-EXCLUDE non-reserved non-reserved non-reserved
-EXCLUDING non-reserved non-reserved non-reserved
-EXCLUSIVE non-reserved
-EXEC reserved reserved reserved
-EXECUTE non-reserved reserved reserved reserved
-EXISTS non-reserved (cannot be function or type) reserved reserved reserved
-EXP reserved reserved
-EXPLAIN non-reserved
-EXPRESSION non-reserved
-EXTENSION non-reserved
-EXTERNAL non-reserved reserved reserved reserved
-EXTRACT non-reserved (cannot be function or type) reserved reserved reserved
-FALSE reserved reserved reserved reserved
-FAMILY non-reserved
-FETCH reserved reserved reserved reserved
-FILE non-reserved non-reserved
-FILTER reserved reserved
-FINAL non-reserved non-reserved
-FIRST non-reserved non-reserved non-reserved reserved
-FIRST_VALUE reserved reserved
-FLAG non-reserved non-reserved
-FLOAT non-reserved (cannot be function or type) reserved reserved reserved
-FLOOR reserved reserved
-FOLLOWING non-reserved non-reserved non-reserved
-FOR reserved reserved reserved reserved
-FORCE non-reserved
-FOREIGN reserved reserved reserved reserved
-FORTRAN non-reserved non-reserved non-reserved
-FORWARD non-reserved
-FOUND non-reserved non-reserved reserved
-FRAME_ROW reserved
-FREE reserved reserved
-FREEZE reserved (can be function or type)
-FROM reserved reserved reserved reserved
-FS non-reserved non-reserved
-FULL reserved (can be function or type) reserved reserved reserved
-FUNCTION non-reserved reserved reserved
-FUNCTIONS non-reserved
-FUSION reserved reserved
-G non-reserved non-reserved
-GENERAL non-reserved non-reserved
-GENERATED non-reserved non-reserved
-GET reserved reserved reserved
-GLOBAL non-reserved reserved reserved reserved
-GO non-reserved non-reserved reserved
-GOTO non-reserved non-reserved reserved
-GRANT reserved reserved reserved reserved
-GRANTED non-reserved non-reserved non-reserved
-GREATEST non-reserved (cannot be function or type)
-GROUP reserved reserved reserved reserved
-GROUPING reserved reserved
-GROUPS reserved
-HANDLER non-reserved
-HAVING reserved reserved reserved reserved
-HEADER non-reserved
-HEX non-reserved non-reserved
-HIERARCHY non-reserved non-reserved
-HOLD non-reserved reserved reserved
-HOUR non-reserved reserved reserved reserved
-ID non-reserved non-reserved
-IDENTITY non-reserved reserved reserved reserved
-IF non-reserved
-IGNORE non-reserved non-reserved
-ILIKE reserved (can be function or type)
-IMMEDIATE non-reserved non-reserved non-reserved reserved
-IMMEDIATELY non-reserved
-IMMUTABLE non-reserved
-IMPLEMENTATION non-reserved non-reserved
-IMPLICIT non-reserved
-IMPORT reserved reserved
-IN reserved reserved reserved reserved
-INCLUDING non-reserved non-reserved non-reserved
-INCREMENT non-reserved non-reserved non-reserved
-INDENT non-reserved non-reserved
-INDEX non-reserved
-INDEXES non-reserved
-INDICATOR reserved reserved reserved
-INHERIT non-reserved
-INHERITS non-reserved
-INITIALLY reserved non-reserved non-reserved reserved
-INLINE non-reserved
-INNER reserved (can be function or type) reserved reserved reserved
-INOUT non-reserved (cannot be function or type) reserved reserved
-INPUT non-reserved non-reserved non-reserved reserved
-INSENSITIVE non-reserved reserved reserved reserved
-INSERT non-reserved reserved reserved reserved
-INSTANCE non-reserved non-reserved
-INSTANTIABLE non-reserved non-reserved
-INSTEAD non-reserved non-reserved non-reserved
-INT non-reserved (cannot be function or type) reserved reserved reserved
-INTEGER non-reserved (cannot be function or type) reserved reserved reserved
-INTEGRITY non-reserved non-reserved
-INTERSECT reserved reserved reserved reserved
-INTERSECTION reserved reserved
-INTERVAL non-reserved (cannot be function or type) reserved reserved reserved
-INTO reserved reserved reserved reserved
-INVOKER non-reserved non-reserved non-reserved
-IS reserved (can be function or type) reserved reserved reserved
-ISNULL reserved (can be function or type)
-ISOLATION non-reserved non-reserved non-reserved reserved
-JOIN reserved (can be function or type) reserved reserved reserved
-K non-reserved non-reserved
-KEY non-reserved non-reserved non-reserved reserved
-KEY_MEMBER non-reserved non-reserved
-KEY_TYPE non-reserved non-reserved
-LABEL non-reserved
-LAG reserved reserved
-LANGUAGE non-reserved reserved reserved reserved
-LARGE non-reserved reserved reserved
-LAST non-reserved non-reserved non-reserved reserved
-LAST_VALUE reserved reserved
-LATERAL reserved reserved reserved
-LC_COLLATE non-reserved
-LC_CTYPE non-reserved
-LEAD reserved reserved
-LEADING reserved reserved reserved reserved
-LEAKPROOF non-reserved
-LEAST non-reserved (cannot be function or type)
-LEFT reserved (can be function or type) reserved reserved reserved
-LENGTH non-reserved non-reserved non-reserved
-LEVEL non-reserved non-reserved non-reserved reserved
-LIBRARY non-reserved non-reserved
-LIKE reserved (can be function or type) reserved reserved reserved
-LIKE_REGEX reserved reserved
-LIMIT reserved non-reserved non-reserved
-LINK non-reserved non-reserved
-LISTEN non-reserved
-LN reserved reserved
-LOAD non-reserved
-LOCAL non-reserved reserved reserved reserved
-LOCALTIME reserved reserved reserved
-LOCALTIMESTAMP reserved reserved reserved
-LOCATION non-reserved non-reserved non-reserved
-LOCATOR non-reserved non-reserved
-LOCK non-reserved
-LOWER reserved reserved reserved
-M non-reserved non-reserved
-MAP non-reserved non-reserved
-MAPPING non-reserved non-reserved non-reserved
-MATCH non-reserved reserved reserved reserved
-MATCHED non-reserved non-reserved
-MATERIALIZED non-reserved
-MAX reserved reserved reserved
-MAXVALUE non-reserved non-reserved non-reserved
-MAX_CARDINALITY reserved
-MEMBER reserved reserved
-MERGE reserved reserved
-MESSAGE_LENGTH non-reserved non-reserved non-reserved
-MESSAGE_OCTET_LENGTH non-reserved non-reserved non-reserved
-MESSAGE_TEXT non-reserved non-reserved non-reserved
-METHOD reserved reserved
-MIN reserved reserved reserved
-MINUTE non-reserved reserved reserved reserved
-MINVALUE non-reserved non-reserved non-reserved
-MOD reserved reserved
-MODE non-reserved
-MODIFIES reserved reserved
-MODULE reserved reserved reserved
-MONTH non-reserved reserved reserved reserved
-MORE non-reserved non-reserved non-reserved
-MOVE non-reserved
-MULTISET reserved reserved
-MUMPS non-reserved non-reserved non-reserved
-NAME non-reserved non-reserved non-reserved non-reserved
-NAMES non-reserved non-reserved non-reserved reserved
-NAMESPACE non-reserved non-reserved
-NATIONAL non-reserved (cannot be function or type) reserved reserved reserved
-NATURAL reserved (can be function or type) reserved reserved reserved
-NCHAR non-reserved (cannot be function or type) reserved reserved reserved
-NCLOB reserved reserved
-NESTING non-reserved non-reserved
-NEW reserved reserved
-NEXT non-reserved non-reserved non-reserved reserved
-NFC non-reserved non-reserved
-NFD non-reserved non-reserved
-NFKC non-reserved non-reserved
-NFKD non-reserved non-reserved
-NIL non-reserved non-reserved
-NO non-reserved reserved reserved reserved
-NONE non-reserved (cannot be function or type) reserved reserved
-NORMALIZE reserved reserved
-NORMALIZED non-reserved non-reserved
-NOT reserved reserved reserved reserved
-NOTHING non-reserved
-NOTIFY non-reserved
-NOTNULL reserved (can be function or type)
-NOWAIT non-reserved
-NTH_VALUE reserved reserved
-NTILE reserved reserved
-NULL reserved reserved reserved reserved
-NULLABLE non-reserved non-reserved non-reserved
-NULLIF non-reserved (cannot be function or type) reserved reserved reserved
-NULLS non-reserved non-reserved non-reserved
-NUMBER non-reserved non-reserved non-reserved
-NUMERIC non-reserved (cannot be function or type) reserved reserved reserved
-OBJECT non-reserved non-reserved non-reserved
-OCCURRENCES_REGEX reserved reserved
-OCTETS non-reserved non-reserved
-OCTET_LENGTH reserved reserved reserved
-OF non-reserved reserved reserved reserved
-OFF non-reserved non-reserved non-reserved
-OFFSET reserved reserved reserved
-OIDS non-reserved
-OLD reserved reserved
-ON reserved reserved reserved reserved
-ONLY reserved reserved reserved reserved
-OPEN reserved reserved reserved
-OPERATOR non-reserved
-OPTION non-reserved non-reserved non-reserved reserved
-OPTIONS non-reserved non-reserved non-reserved
-OR reserved reserved reserved reserved
-ORDER reserved reserved reserved reserved
-ORDERING non-reserved non-reserved
-ORDINALITY non-reserved non-reserved
-OTHERS non-reserved non-reserved
-OUT non-reserved (cannot be function or type) reserved reserved
-OUTER reserved (can be function or type) reserved reserved reserved
-OUTPUT non-reserved non-reserved reserved
-OVER reserved (can be function or type) reserved reserved
-OVERLAPS reserved (can be function or type) reserved reserved reserved
-OVERLAY non-reserved (cannot be function or type) reserved reserved
-OVERRIDING non-reserved non-reserved
-OWNED non-reserved
-OWNER non-reserved
-P non-reserved non-reserved
-PAD non-reserved non-reserved reserved
-PARAMETER reserved reserved
-PARAMETER_MODE non-reserved non-reserved
-PARAMETER_NAME non-reserved non-reserved
-PARAMETER_ORDINAL_POSITION non-reserved non-reserved
-PARAMETER_SPECIFIC_CATALOG non-reserved non-reserved
-PARAMETER_SPECIFIC_NAME non-reserved non-reserved
-PARAMETER_SPECIFIC_SCHEMA non-reserved non-reserved
-PARSER non-reserved
-PARTIAL non-reserved non-reserved non-reserved reserved
-PARTITION non-reserved reserved reserved
-PASCAL non-reserved non-reserved non-reserved
-PASSING non-reserved non-reserved non-reserved
-PASSTHROUGH non-reserved non-reserved
-PASSWORD non-reserved
-PATH non-reserved non-reserved
-PERCENT reserved
-PERCENTILE_CONT reserved reserved
-PERCENTILE_DISC reserved reserved
-PERCENT_RANK reserved reserved
-PERIOD reserved
-PERMISSION non-reserved non-reserved
-PLACING reserved non-reserved non-reserved
-PLANS non-reserved
-PLI non-reserved non-reserved non-reserved
-PORTION reserved
-POSITION non-reserved (cannot be function or type) reserved reserved reserved
-POSITION_REGEX reserved reserved
-POWER reserved reserved
-PRECEDES reserved
-PRECEDING non-reserved non-reserved non-reserved
-PRECISION non-reserved (cannot be function or type) reserved reserved reserved
-PREPARE non-reserved reserved reserved reserved
-PREPARED non-reserved
-PRESERVE non-reserved non-reserved non-reserved reserved
-PRIMARY reserved reserved reserved reserved
-PRIOR non-reserved non-reserved non-reserved reserved
-PRIVILEGES non-reserved non-reserved non-reserved reserved
-PROCEDURAL non-reserved
-PROCEDURE non-reserved reserved reserved reserved
-PROGRAM non-reserved
-PUBLIC non-reserved non-reserved reserved
-QUOTE non-reserved
-RANGE non-reserved reserved reserved
-RANK reserved reserved
-READ non-reserved non-reserved non-reserved reserved
-READS reserved reserved
-REAL non-reserved (cannot be function or type) reserved reserved reserved
-REASSIGN non-reserved
-RECHECK non-reserved
-RECOVERY non-reserved non-reserved
-RECURSIVE non-reserved reserved reserved
-REF non-reserved reserved reserved
-REFERENCES reserved reserved reserved reserved
-REFERENCING reserved reserved
-REFRESH non-reserved
-REGR_AVGX reserved reserved
-REGR_AVGY reserved reserved
-REGR_COUNT reserved reserved
-REGR_INTERCEPT reserved reserved
-REGR_R2 reserved reserved
-REGR_SLOPE reserved reserved
-REGR_SXX reserved reserved
-REGR_SXY reserved reserved
-REGR_SYY reserved reserved
-REINDEX non-reserved
-RELATIVE non-reserved non-reserved non-reserved reserved
-RELEASE non-reserved reserved reserved
-RENAME non-reserved
-REPEATABLE non-reserved non-reserved non-reserved non-reserved
-REPLACE non-reserved
-REPLICA non-reserved
-REQUIRING non-reserved non-reserved
-RESET non-reserved
-RESPECT non-reserved non-reserved
-RESTART non-reserved non-reserved non-reserved
-RESTORE non-reserved non-reserved
-RESTRICT non-reserved non-reserved non-reserved reserved
-RESULT reserved reserved
-RETURN reserved reserved
-RETURNED_CARDINALITY non-reserved non-reserved
-RETURNED_LENGTH non-reserved non-reserved non-reserved
-RETURNED_OCTET_LENGTH non-reserved non-reserved non-reserved
-RETURNED_SQLSTATE non-reserved non-reserved non-reserved
-RETURNING reserved non-reserved non-reserved
-RETURNS non-reserved reserved reserved
-REVOKE non-reserved reserved reserved reserved
-RIGHT reserved (can be function or type) reserved reserved reserved
-ROLE non-reserved non-reserved non-reserved
-ROLLBACK non-reserved reserved reserved reserved
-ROLLUP reserved reserved
-ROUTINE non-reserved non-reserved
-ROUTINE_CATALOG non-reserved non-reserved
-ROUTINE_NAME non-reserved non-reserved
-ROUTINE_SCHEMA non-reserved non-reserved
-ROW non-reserved (cannot be function or type) reserved reserved
-ROWS non-reserved reserved reserved reserved
-ROW_COUNT non-reserved non-reserved non-reserved
-ROW_NUMBER reserved reserved
-RULE non-reserved
-SAVEPOINT non-reserved reserved reserved
-SCALE non-reserved non-reserved non-reserved
-SCHEMA non-reserved non-reserved non-reserved reserved
-SCHEMA_NAME non-reserved non-reserved non-reserved
-SCOPE reserved reserved
-SCOPE_CATALOG non-reserved non-reserved
-SCOPE_NAME non-reserved non-reserved
-SCOPE_SCHEMA non-reserved non-reserved
-SCROLL non-reserved reserved reserved reserved
-SEARCH non-reserved reserved reserved
-SECOND non-reserved reserved reserved reserved
-SECTION non-reserved non-reserved reserved
-SECURITY non-reserved non-reserved non-reserved
-SELECT reserved reserved reserved reserved
-SELECTIVE non-reserved non-reserved
-SELF non-reserved non-reserved
-SENSITIVE reserved reserved
-SEQUENCE non-reserved non-reserved non-reserved
-SEQUENCES non-reserved
-SERIALIZABLE non-reserved non-reserved non-reserved non-reserved
-SERVER non-reserved non-reserved non-reserved
-SERVER_NAME non-reserved non-reserved non-reserved
-SESSION non-reserved non-reserved non-reserved reserved
-SESSION_USER reserved reserved reserved reserved
-SET non-reserved reserved reserved reserved
-SETOF non-reserved (cannot be function or type)
-SETS non-reserved non-reserved
-SHARE non-reserved
-SHOW non-reserved
-SIMILAR reserved (can be function or type) reserved reserved
-SIMPLE non-reserved non-reserved non-reserved
-SIZE non-reserved non-reserved reserved
-SMALLINT non-reserved (cannot be function or type) reserved reserved reserved
-SNAPSHOT non-reserved
-SOME reserved reserved reserved reserved
-SOURCE non-reserved non-reserved
-SPACE non-reserved non-reserved reserved
-SPECIFIC reserved reserved
-SPECIFICTYPE reserved reserved
-SPECIFIC_NAME non-reserved non-reserved
-SQL reserved reserved reserved
-SQLCODE reserved
-SQLERROR reserved
-SQLEXCEPTION reserved reserved
-SQLSTATE reserved reserved reserved
-SQLWARNING reserved reserved
-SQRT reserved reserved
-STABLE non-reserved
-STANDALONE non-reserved non-reserved non-reserved
-START non-reserved reserved reserved
-STATE non-reserved non-reserved
-STATEMENT non-reserved non-reserved non-reserved
-STATIC reserved reserved
-STATISTICS non-reserved
-STDDEV_POP reserved reserved
-STDDEV_SAMP reserved reserved
-STDIN non-reserved
-STDOUT non-reserved
-STORAGE non-reserved
-STRICT non-reserved
-STRIP non-reserved non-reserved non-reserved
-STRUCTURE non-reserved non-reserved
-STYLE non-reserved non-reserved
-SUBCLASS_ORIGIN non-reserved non-reserved non-reserved
-SUBMULTISET reserved reserved
-SUBSTRING non-reserved (cannot be function or type) reserved reserved reserved
-SUBSTRING_REGEX reserved reserved
-SUCCEEDS reserved
-SUM reserved reserved reserved
-SYMMETRIC reserved reserved reserved
-SYSID non-reserved
-SYSTEM non-reserved reserved reserved
-SYSTEM_TIME reserved
-SYSTEM_USER reserved reserved reserved
-T non-reserved non-reserved
-TABLE reserved reserved reserved reserved
-TABLES non-reserved
-TABLESAMPLE reserved reserved
-TABLESPACE non-reserved
-TABLE_NAME non-reserved non-reserved non-reserved
-TEMP non-reserved
-TEMPLATE non-reserved
-TEMPORARY non-reserved non-reserved non-reserved reserved
-TEXT non-reserved
-THEN reserved reserved reserved reserved
-TIES non-reserved non-reserved
-TIME non-reserved (cannot be function or type) reserved reserved reserved
-TIMESTAMP non-reserved (cannot be function or type) reserved reserved reserved
-TIMEZONE_HOUR reserved reserved reserved
-TIMEZONE_MINUTE reserved reserved reserved
-TO reserved reserved reserved reserved
-TOKEN non-reserved non-reserved
-TOP_LEVEL_COUNT non-reserved non-reserved
-TRAILING reserved reserved reserved reserved
-TRANSACTION non-reserved non-reserved non-reserved reserved
-TRANSACTIONS_COMMITTED non-reserved non-reserved
-TRANSACTIONS_ROLLED_BACK non-reserved non-reserved
-TRANSACTION_ACTIVE non-reserved non-reserved
-TRANSFORM non-reserved non-reserved
-TRANSFORMS non-reserved non-reserved
-TRANSLATE reserved reserved reserved
-TRANSLATE_REGEX reserved reserved
-TRANSLATION reserved reserved reserved
-TREAT non-reserved (cannot be function or type) reserved reserved
-TRIGGER non-reserved reserved reserved
-TRIGGER_CATALOG non-reserved non-reserved
-TRIGGER_NAME non-reserved non-reserved
-TRIGGER_SCHEMA non-reserved non-reserved
-TRIM non-reserved (cannot be function or type) reserved reserved reserved
-TRIM_ARRAY reserved reserved
-TRUE reserved reserved reserved reserved
-TRUNCATE non-reserved reserved reserved
-TRUSTED non-reserved
-TYPE non-reserved non-reserved non-reserved non-reserved
-TYPES non-reserved
-UESCAPE reserved reserved
-UNBOUNDED non-reserved non-reserved non-reserved
-UNCOMMITTED non-reserved non-reserved non-reserved non-reserved
-UNDER non-reserved non-reserved
-UNENCRYPTED non-reserved
-UNION reserved reserved reserved reserved
-UNIQUE reserved reserved reserved reserved
-UNKNOWN non-reserved reserved reserved reserved
-UNLINK non-reserved non-reserved
-UNLISTEN non-reserved
-UNLOGGED non-reserved
-UNNAMED non-reserved non-reserved non-reserved
-UNNEST reserved reserved
-UNTIL non-reserved
-UNTYPED non-reserved non-reserved
-UPDATE non-reserved reserved reserved reserved
-UPPER reserved reserved reserved
-URI non-reserved non-reserved
-USAGE non-reserved non-reserved reserved
-USER reserved reserved reserved reserved
-USER_DEFINED_TYPE_CATALOG non-reserved non-reserved
-USER_DEFINED_TYPE_CODE non-reserved non-reserved
-USER_DEFINED_TYPE_NAME non-reserved non-reserved
-USER_DEFINED_TYPE_SCHEMA non-reserved non-reserved
-USING reserved reserved reserved reserved
-VACUUM non-reserved
-VALID non-reserved non-reserved non-reserved
-VALIDATE non-reserved
-VALIDATOR non-reserved
-VALUE non-reserved reserved reserved reserved
-VALUES non-reserved (cannot be function or type) reserved reserved reserved
-VALUE_OF reserved
-VARBINARY reserved reserved
-VARCHAR non-reserved (cannot be function or type) reserved reserved reserved
-VARIADIC reserved
-VARYING non-reserved reserved reserved reserved
-VAR_POP reserved reserved
-VAR_SAMP reserved reserved
-VERBOSE reserved (can be function or type)
-VERSION non-reserved non-reserved non-reserved
-VERSIONING reserved
-VIEW non-reserved non-reserved non-reserved reserved
-VOLATILE non-reserved
-WHEN reserved reserved reserved reserved
-WHENEVER reserved reserved reserved
-WHERE reserved reserved reserved reserved
-WHITESPACE non-reserved non-reserved non-reserved
-WIDTH_BUCKET reserved reserved
-WINDOW reserved reserved reserved
-WITH reserved reserved reserved reserved
-WITHIN reserved reserved
-WITHOUT non-reserved reserved reserved
-WORK non-reserved non-reserved non-reserved reserved
-WRAPPER non-reserved non-reserved non-reserved
-WRITE non-reserved non-reserved non-reserved reserved
-XML non-reserved reserved reserved
-XMLAGG reserved reserved
-XMLATTRIBUTES non-reserved (cannot be function or type) reserved reserved
-XMLBINARY reserved reserved
-XMLCAST reserved reserved
-XMLCOMMENT reserved reserved
-XMLCONCAT non-reserved (cannot be function or type) reserved reserved
-XMLDECLARATION non-reserved non-reserved
-XMLDOCUMENT reserved reserved
-XMLELEMENT non-reserved (cannot be function or type) reserved reserved
-XMLEXISTS non-reserved (cannot be function or type) reserved reserved
-XMLFOREST non-reserved (cannot be function or type) reserved reserved
-XMLITERATE reserved reserved
-XMLNAMESPACES reserved reserved
-XMLPARSE non-reserved (cannot be function or type) reserved reserved
-XMLPI non-reserved (cannot be function or type) reserved reserved
-XMLQUERY reserved reserved
-XMLROOT non-reserved (cannot be function or type)
-XMLSCHEMA non-reserved non-reserved
-XMLSERIALIZE non-reserved (cannot be function or type) reserved reserved
-XMLTABLE reserved reserved
-XMLTEXT reserved reserved
-XMLVALIDATE reserved reserved
-YEAR non-reserved reserved reserved reserved
-YES non-reserved non-reserved non-reserved
-ZONE non-reserved non-reserved non-reserved reserved
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/processors.go b/vendor/github.com/go-xorm/xorm/processors.go
deleted file mode 100644
index dcd9c6a..0000000
--- a/vendor/github.com/go-xorm/xorm/processors.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-// BeforeInsertProcessor executed before an object is initially persisted to the database
-type BeforeInsertProcessor interface {
- BeforeInsert()
-}
-
-// BeforeUpdateProcessor executed before an object is updated
-type BeforeUpdateProcessor interface {
- BeforeUpdate()
-}
-
-// BeforeDeleteProcessor executed before an object is deleted
-type BeforeDeleteProcessor interface {
- BeforeDelete()
-}
-
-// BeforeSetProcessor executed before data set to the struct fields
-type BeforeSetProcessor interface {
- BeforeSet(string, Cell)
-}
-
-// AfterSetProcessor executed after data set to the struct fields
-type AfterSetProcessor interface {
- AfterSet(string, Cell)
-}
-
-// AfterInsertProcessor executed after an object is persisted to the database
-type AfterInsertProcessor interface {
- AfterInsert()
-}
-
-// AfterUpdateProcessor executed after an object has been updated
-type AfterUpdateProcessor interface {
- AfterUpdate()
-}
-
-// AfterDeleteProcessor executed after an object has been deleted
-type AfterDeleteProcessor interface {
- AfterDelete()
-}
-
-// AfterLoadProcessor executed after an ojbect has been loaded from database
-type AfterLoadProcessor interface {
- AfterLoad()
-}
-
-// AfterLoadSessionProcessor executed after an ojbect has been loaded from database with session parameter
-type AfterLoadSessionProcessor interface {
- AfterLoad(*Session)
-}
-
-type executedProcessorFunc func(*Session, interface{}) error
-
-type executedProcessor struct {
- fun executedProcessorFunc
- session *Session
- bean interface{}
-}
-
-func (executor *executedProcessor) execute() error {
- return executor.fun(executor.session, executor.bean)
-}
-
-func (session *Session) executeProcessors() error {
- processors := session.afterProcessors
- session.afterProcessors = make([]executedProcessor, 0)
- for _, processor := range processors {
- if err := processor.execute(); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/rows.go b/vendor/github.com/go-xorm/xorm/rows.go
deleted file mode 100644
index bdd4458..0000000
--- a/vendor/github.com/go-xorm/xorm/rows.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "fmt"
- "reflect"
-
- "xorm.io/core"
-)
-
-// Rows rows wrapper a rows to
-type Rows struct {
- session *Session
- rows *core.Rows
- beanType reflect.Type
- lastError error
-}
-
-func newRows(session *Session, bean interface{}) (*Rows, error) {
- rows := new(Rows)
- rows.session = session
- rows.beanType = reflect.Indirect(reflect.ValueOf(bean)).Type()
-
- var sqlStr string
- var args []interface{}
- var err error
-
- if err = rows.session.statement.setRefBean(bean); err != nil {
- return nil, err
- }
-
- if len(session.statement.TableName()) <= 0 {
- return nil, ErrTableNotFound
- }
-
- if rows.session.statement.RawSQL == "" {
- sqlStr, args, err = rows.session.statement.genGetSQL(bean)
- if err != nil {
- return nil, err
- }
- } else {
- sqlStr = rows.session.statement.RawSQL
- args = rows.session.statement.RawParams
- }
-
- rows.rows, err = rows.session.queryRows(sqlStr, args...)
- if err != nil {
- rows.lastError = err
- rows.Close()
- return nil, err
- }
-
- return rows, nil
-}
-
-// Next move cursor to next record, return false if end has reached
-func (rows *Rows) Next() bool {
- if rows.lastError == nil && rows.rows != nil {
- hasNext := rows.rows.Next()
- if !hasNext {
- rows.lastError = sql.ErrNoRows
- }
- return hasNext
- }
- return false
-}
-
-// Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
-func (rows *Rows) Err() error {
- return rows.lastError
-}
-
-// Scan row record to bean properties
-func (rows *Rows) Scan(bean interface{}) error {
- if rows.lastError != nil {
- return rows.lastError
- }
-
- if reflect.Indirect(reflect.ValueOf(bean)).Type() != rows.beanType {
- return fmt.Errorf("scan arg is incompatible type to [%v]", rows.beanType)
- }
-
- if err := rows.session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- fields, err := rows.rows.Columns()
- if err != nil {
- return err
- }
-
- scanResults, err := rows.session.row2Slice(rows.rows, fields, bean)
- if err != nil {
- return err
- }
-
- dataStruct := rValue(bean)
- _, err = rows.session.slice2Bean(scanResults, fields, bean, &dataStruct, rows.session.statement.RefTable)
- if err != nil {
- return err
- }
-
- return rows.session.executeProcessors()
-}
-
-// Close session if session.IsAutoClose is true, and claimed any opened resources
-func (rows *Rows) Close() error {
- if rows.session.isAutoClose {
- defer rows.session.Close()
- }
-
- if rows.rows != nil {
- return rows.rows.Close()
- }
-
- return rows.lastError
-}
diff --git a/vendor/github.com/go-xorm/xorm/session.go b/vendor/github.com/go-xorm/xorm/session.go
deleted file mode 100644
index b33955f..0000000
--- a/vendor/github.com/go-xorm/xorm/session.go
+++ /dev/null
@@ -1,866 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "context"
- "database/sql"
- "errors"
- "fmt"
- "hash/crc32"
- "reflect"
- "strings"
- "time"
-
- "xorm.io/core"
-)
-
-type sessionType int
-
-const (
- engineSession sessionType = iota
- groupSession
-)
-
-// Session keep a pointer to sql.DB and provides all execution of all
-// kind of database operations.
-type Session struct {
- db *core.DB
- engine *Engine
- tx *core.Tx
- statement Statement
- isAutoCommit bool
- isCommitedOrRollbacked bool
- isAutoClose bool
-
- // Automatically reset the statement after operations that execute a SQL
- // query such as Count(), Find(), Get(), ...
- autoResetStatement bool
-
- // !nashtsai! storing these beans due to yet committed tx
- afterInsertBeans map[interface{}]*[]func(interface{})
- afterUpdateBeans map[interface{}]*[]func(interface{})
- afterDeleteBeans map[interface{}]*[]func(interface{})
- // --
-
- beforeClosures []func(interface{})
- afterClosures []func(interface{})
-
- afterProcessors []executedProcessor
-
- prepareStmt bool
- stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr))
-
- // !evalphobia! stored the last executed query on this session
- //beforeSQLExec func(string, ...interface{})
- lastSQL string
- lastSQLArgs []interface{}
-
- ctx context.Context
- sessionType sessionType
-}
-
-// Clone copy all the session's content and return a new session
-func (session *Session) Clone() *Session {
- var sess = *session
- return &sess
-}
-
-// Init reset the session as the init status.
-func (session *Session) Init() {
- session.statement.Init()
- session.statement.Engine = session.engine
- session.isAutoCommit = true
- session.isCommitedOrRollbacked = false
- session.isAutoClose = false
- session.autoResetStatement = true
- session.prepareStmt = false
-
- // !nashtsai! is lazy init better?
- session.afterInsertBeans = make(map[interface{}]*[]func(interface{}), 0)
- session.afterUpdateBeans = make(map[interface{}]*[]func(interface{}), 0)
- session.afterDeleteBeans = make(map[interface{}]*[]func(interface{}), 0)
- session.beforeClosures = make([]func(interface{}), 0)
- session.afterClosures = make([]func(interface{}), 0)
- session.stmtCache = make(map[uint32]*core.Stmt)
-
- session.afterProcessors = make([]executedProcessor, 0)
-
- session.lastSQL = ""
- session.lastSQLArgs = []interface{}{}
-
- session.ctx = session.engine.defaultContext
-}
-
-// Close release the connection from pool
-func (session *Session) Close() {
- for _, v := range session.stmtCache {
- v.Close()
- }
-
- if session.db != nil {
- // When Close be called, if session is a transaction and do not call
- // Commit or Rollback, then call Rollback.
- if session.tx != nil && !session.isCommitedOrRollbacked {
- session.Rollback()
- }
- session.tx = nil
- session.stmtCache = nil
- session.db = nil
- }
-}
-
-// ContextCache enable context cache or not
-func (session *Session) ContextCache(context ContextCache) *Session {
- session.statement.context = context
- return session
-}
-
-// IsClosed returns if session is closed
-func (session *Session) IsClosed() bool {
- return session.db == nil
-}
-
-func (session *Session) resetStatement() {
- if session.autoResetStatement {
- session.statement.Init()
- }
-}
-
-// Prepare set a flag to session that should be prepare statement before execute query
-func (session *Session) Prepare() *Session {
- session.prepareStmt = true
- return session
-}
-
-// Before Apply before Processor, affected bean is passed to closure arg
-func (session *Session) Before(closures func(interface{})) *Session {
- if closures != nil {
- session.beforeClosures = append(session.beforeClosures, closures)
- }
- return session
-}
-
-// After Apply after Processor, affected bean is passed to closure arg
-func (session *Session) After(closures func(interface{})) *Session {
- if closures != nil {
- session.afterClosures = append(session.afterClosures, closures)
- }
- return session
-}
-
-// Table can input a string or pointer to struct for special a table to operate.
-func (session *Session) Table(tableNameOrBean interface{}) *Session {
- session.statement.Table(tableNameOrBean)
- return session
-}
-
-// Alias set the table alias
-func (session *Session) Alias(alias string) *Session {
- session.statement.Alias(alias)
- return session
-}
-
-// NoCascade indicate that no cascade load child object
-func (session *Session) NoCascade() *Session {
- session.statement.UseCascade = false
- return session
-}
-
-// ForUpdate Set Read/Write locking for UPDATE
-func (session *Session) ForUpdate() *Session {
- session.statement.IsForUpdate = true
- return session
-}
-
-// NoAutoCondition disable generate SQL condition from beans
-func (session *Session) NoAutoCondition(no ...bool) *Session {
- session.statement.NoAutoCondition(no...)
- return session
-}
-
-// Limit provide limit and offset query condition
-func (session *Session) Limit(limit int, start ...int) *Session {
- session.statement.Limit(limit, start...)
- return session
-}
-
-// OrderBy provide order by query condition, the input parameter is the content
-// after order by on a sql statement.
-func (session *Session) OrderBy(order string) *Session {
- session.statement.OrderBy(order)
- return session
-}
-
-// Desc provide desc order by query condition, the input parameters are columns.
-func (session *Session) Desc(colNames ...string) *Session {
- session.statement.Desc(colNames...)
- return session
-}
-
-// Asc provide asc order by query condition, the input parameters are columns.
-func (session *Session) Asc(colNames ...string) *Session {
- session.statement.Asc(colNames...)
- return session
-}
-
-// StoreEngine is only avialble mysql dialect currently
-func (session *Session) StoreEngine(storeEngine string) *Session {
- session.statement.StoreEngine = storeEngine
- return session
-}
-
-// Charset is only avialble mysql dialect currently
-func (session *Session) Charset(charset string) *Session {
- session.statement.Charset = charset
- return session
-}
-
-// Cascade indicates if loading sub Struct
-func (session *Session) Cascade(trueOrFalse ...bool) *Session {
- if len(trueOrFalse) >= 1 {
- session.statement.UseCascade = trueOrFalse[0]
- }
- return session
-}
-
-// NoCache ask this session do not retrieve data from cache system and
-// get data from database directly.
-func (session *Session) NoCache() *Session {
- session.statement.UseCache = false
- return session
-}
-
-// Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
-func (session *Session) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
- session.statement.Join(joinOperator, tablename, condition, args...)
- return session
-}
-
-// GroupBy Generate Group By statement
-func (session *Session) GroupBy(keys string) *Session {
- session.statement.GroupBy(keys)
- return session
-}
-
-// Having Generate Having statement
-func (session *Session) Having(conditions string) *Session {
- session.statement.Having(conditions)
- return session
-}
-
-// DB db return the wrapper of sql.DB
-func (session *Session) DB() *core.DB {
- if session.db == nil {
- session.db = session.engine.db
- session.stmtCache = make(map[uint32]*core.Stmt, 0)
- }
- return session.db
-}
-
-func cleanupProcessorsClosures(slices *[]func(interface{})) {
- if len(*slices) > 0 {
- *slices = make([]func(interface{}), 0)
- }
-}
-
-func (session *Session) canCache() bool {
- if session.statement.RefTable == nil ||
- session.statement.JoinStr != "" ||
- session.statement.RawSQL != "" ||
- !session.statement.UseCache ||
- session.statement.IsForUpdate ||
- session.tx != nil ||
- len(session.statement.selectStr) > 0 {
- return false
- }
- return true
-}
-
-func (session *Session) doPrepare(db *core.DB, sqlStr string) (stmt *core.Stmt, err error) {
- crc := crc32.ChecksumIEEE([]byte(sqlStr))
- // TODO try hash(sqlStr+len(sqlStr))
- var has bool
- stmt, has = session.stmtCache[crc]
- if !has {
- stmt, err = db.PrepareContext(session.ctx, sqlStr)
- if err != nil {
- return nil, err
- }
- session.stmtCache[crc] = stmt
- }
- return
-}
-
-func (session *Session) getField(dataStruct *reflect.Value, key string, table *core.Table, idx int) (*reflect.Value, error) {
- var col *core.Column
- if col = table.GetColumnIdx(key, idx); col == nil {
- return nil, ErrFieldIsNotExist{key, table.Name}
- }
-
- fieldValue, err := col.ValueOfV(dataStruct)
- if err != nil {
- return nil, err
- }
-
- if !fieldValue.IsValid() || !fieldValue.CanSet() {
- return nil, ErrFieldIsNotValid{key, table.Name}
- }
-
- return fieldValue, nil
-}
-
-// Cell cell is a result of one column field
-type Cell *interface{}
-
-func (session *Session) rows2Beans(rows *core.Rows, fields []string,
- table *core.Table, newElemFunc func([]string) reflect.Value,
- sliceValueSetFunc func(*reflect.Value, core.PK) error) error {
- for rows.Next() {
- var newValue = newElemFunc(fields)
- bean := newValue.Interface()
- dataStruct := newValue.Elem()
-
- // handle beforeClosures
- scanResults, err := session.row2Slice(rows, fields, bean)
- if err != nil {
- return err
- }
- pk, err := session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
- if err != nil {
- return err
- }
- session.afterProcessors = append(session.afterProcessors, executedProcessor{
- fun: func(*Session, interface{}) error {
- return sliceValueSetFunc(&newValue, pk)
- },
- session: session,
- bean: bean,
- })
- }
- return nil
-}
-
-func (session *Session) row2Slice(rows *core.Rows, fields []string, bean interface{}) ([]interface{}, error) {
- for _, closure := range session.beforeClosures {
- closure(bean)
- }
-
- scanResults := make([]interface{}, len(fields))
- for i := 0; i < len(fields); i++ {
- var cell interface{}
- scanResults[i] = &cell
- }
- if err := rows.Scan(scanResults...); err != nil {
- return nil, err
- }
-
- if b, hasBeforeSet := bean.(BeforeSetProcessor); hasBeforeSet {
- for ii, key := range fields {
- b.BeforeSet(key, Cell(scanResults[ii].(*interface{})))
- }
- }
- return scanResults, nil
-}
-
-func (session *Session) slice2Bean(scanResults []interface{}, fields []string, bean interface{}, dataStruct *reflect.Value, table *core.Table) (core.PK, error) {
- defer func() {
- if b, hasAfterSet := bean.(AfterSetProcessor); hasAfterSet {
- for ii, key := range fields {
- b.AfterSet(key, Cell(scanResults[ii].(*interface{})))
- }
- }
- }()
-
- // handle afterClosures
- for _, closure := range session.afterClosures {
- session.afterProcessors = append(session.afterProcessors, executedProcessor{
- fun: func(sess *Session, bean interface{}) error {
- closure(bean)
- return nil
- },
- session: session,
- bean: bean,
- })
- }
-
- if a, has := bean.(AfterLoadProcessor); has {
- session.afterProcessors = append(session.afterProcessors, executedProcessor{
- fun: func(sess *Session, bean interface{}) error {
- a.AfterLoad()
- return nil
- },
- session: session,
- bean: bean,
- })
- }
-
- if a, has := bean.(AfterLoadSessionProcessor); has {
- session.afterProcessors = append(session.afterProcessors, executedProcessor{
- fun: func(sess *Session, bean interface{}) error {
- a.AfterLoad(sess)
- return nil
- },
- session: session,
- bean: bean,
- })
- }
-
- var tempMap = make(map[string]int)
- var pk core.PK
- for ii, key := range fields {
- var idx int
- var ok bool
- var lKey = strings.ToLower(key)
- if idx, ok = tempMap[lKey]; !ok {
- idx = 0
- } else {
- idx = idx + 1
- }
- tempMap[lKey] = idx
-
- fieldValue, err := session.getField(dataStruct, key, table, idx)
- if err != nil {
- if !strings.Contains(err.Error(), "is not valid") {
- session.engine.logger.Warn(err)
- }
- continue
- }
- if fieldValue == nil {
- continue
- }
- rawValue := reflect.Indirect(reflect.ValueOf(scanResults[ii]))
-
- // if row is null then ignore
- if rawValue.Interface() == nil {
- continue
- }
-
- if fieldValue.CanAddr() {
- if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
- if data, err := value2Bytes(&rawValue); err == nil {
- if err := structConvert.FromDB(data); err != nil {
- return nil, err
- }
- } else {
- return nil, err
- }
- continue
- }
- }
-
- if _, ok := fieldValue.Interface().(core.Conversion); ok {
- if data, err := value2Bytes(&rawValue); err == nil {
- if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
- fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
- }
- fieldValue.Interface().(core.Conversion).FromDB(data)
- } else {
- return nil, err
- }
- continue
- }
-
- rawValueType := reflect.TypeOf(rawValue.Interface())
- vv := reflect.ValueOf(rawValue.Interface())
- col := table.GetColumnIdx(key, idx)
- if col.IsPrimaryKey {
- pk = append(pk, rawValue.Interface())
- }
- fieldType := fieldValue.Type()
- hasAssigned := false
-
- if col.SQLType.IsJson() {
- var bs []byte
- if rawValueType.Kind() == reflect.String {
- bs = []byte(vv.String())
- } else if rawValueType.ConvertibleTo(core.BytesType) {
- bs = vv.Bytes()
- } else {
- return nil, fmt.Errorf("unsupported database data type: %s %v", key, rawValueType.Kind())
- }
-
- hasAssigned = true
-
- if len(bs) > 0 {
- if fieldType.Kind() == reflect.String {
- fieldValue.SetString(string(bs))
- continue
- }
- if fieldValue.CanAddr() {
- err := DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
- if err != nil {
- return nil, err
- }
- } else {
- x := reflect.New(fieldType)
- err := DefaultJSONHandler.Unmarshal(bs, x.Interface())
- if err != nil {
- return nil, err
- }
- fieldValue.Set(x.Elem())
- }
- }
-
- continue
- }
-
- switch fieldType.Kind() {
- case reflect.Complex64, reflect.Complex128:
- // TODO: reimplement this
- var bs []byte
- if rawValueType.Kind() == reflect.String {
- bs = []byte(vv.String())
- } else if rawValueType.ConvertibleTo(core.BytesType) {
- bs = vv.Bytes()
- }
-
- hasAssigned = true
- if len(bs) > 0 {
- if fieldValue.CanAddr() {
- err := DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
- if err != nil {
- return nil, err
- }
- } else {
- x := reflect.New(fieldType)
- err := DefaultJSONHandler.Unmarshal(bs, x.Interface())
- if err != nil {
- return nil, err
- }
- fieldValue.Set(x.Elem())
- }
- }
- case reflect.Slice, reflect.Array:
- switch rawValueType.Kind() {
- case reflect.Slice, reflect.Array:
- switch rawValueType.Elem().Kind() {
- case reflect.Uint8:
- if fieldType.Elem().Kind() == reflect.Uint8 {
- hasAssigned = true
- if col.SQLType.IsText() {
- x := reflect.New(fieldType)
- err := DefaultJSONHandler.Unmarshal(vv.Bytes(), x.Interface())
- if err != nil {
- return nil, err
- }
- fieldValue.Set(x.Elem())
- } else {
- if fieldValue.Len() > 0 {
- for i := 0; i < fieldValue.Len(); i++ {
- if i < vv.Len() {
- fieldValue.Index(i).Set(vv.Index(i))
- }
- }
- } else {
- for i := 0; i < vv.Len(); i++ {
- fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
- }
- }
- }
- }
- }
- }
- case reflect.String:
- if rawValueType.Kind() == reflect.String {
- hasAssigned = true
- fieldValue.SetString(vv.String())
- }
- case reflect.Bool:
- if rawValueType.Kind() == reflect.Bool {
- hasAssigned = true
- fieldValue.SetBool(vv.Bool())
- }
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- switch rawValueType.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- hasAssigned = true
- fieldValue.SetInt(vv.Int())
- }
- case reflect.Float32, reflect.Float64:
- switch rawValueType.Kind() {
- case reflect.Float32, reflect.Float64:
- hasAssigned = true
- fieldValue.SetFloat(vv.Float())
- }
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- switch rawValueType.Kind() {
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- hasAssigned = true
- fieldValue.SetUint(vv.Uint())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- hasAssigned = true
- fieldValue.SetUint(uint64(vv.Int()))
- }
- case reflect.Struct:
- if fieldType.ConvertibleTo(core.TimeType) {
- dbTZ := session.engine.DatabaseTZ
- if col.TimeZone != nil {
- dbTZ = col.TimeZone
- }
-
- if rawValueType == core.TimeType {
- hasAssigned = true
-
- t := vv.Convert(core.TimeType).Interface().(time.Time)
-
- z, _ := t.Zone()
- // set new location if database don't save timezone or give an incorrect timezone
- if len(z) == 0 || t.Year() == 0 || t.Location().String() != dbTZ.String() { // !nashtsai! HACK tmp work around for lib/pq doesn't properly time with location
- session.engine.logger.Debugf("empty zone key[%v] : %v | zone: %v | location: %+v\n", key, t, z, *t.Location())
- t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
- t.Minute(), t.Second(), t.Nanosecond(), dbTZ)
- }
-
- t = t.In(session.engine.TZLocation)
- fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
- } else if rawValueType == core.IntType || rawValueType == core.Int64Type ||
- rawValueType == core.Int32Type {
- hasAssigned = true
-
- t := time.Unix(vv.Int(), 0).In(session.engine.TZLocation)
- fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
- } else {
- if d, ok := vv.Interface().([]uint8); ok {
- hasAssigned = true
- t, err := session.byte2Time(col, d)
- if err != nil {
- session.engine.logger.Error("byte2Time error:", err.Error())
- hasAssigned = false
- } else {
- fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
- }
- } else if d, ok := vv.Interface().(string); ok {
- hasAssigned = true
- t, err := session.str2Time(col, d)
- if err != nil {
- session.engine.logger.Error("byte2Time error:", err.Error())
- hasAssigned = false
- } else {
- fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
- }
- } else {
- return nil, fmt.Errorf("rawValueType is %v, value is %v", rawValueType, vv.Interface())
- }
- }
- } else if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
- // !! 增加支持sql.Scanner接口的结构,如sql.NullString
- hasAssigned = true
- if err := nulVal.Scan(vv.Interface()); err != nil {
- session.engine.logger.Error("sql.Sanner error:", err.Error())
- hasAssigned = false
- }
- } else if col.SQLType.IsJson() {
- if rawValueType.Kind() == reflect.String {
- hasAssigned = true
- x := reflect.New(fieldType)
- if len([]byte(vv.String())) > 0 {
- err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), x.Interface())
- if err != nil {
- return nil, err
- }
- fieldValue.Set(x.Elem())
- }
- } else if rawValueType.Kind() == reflect.Slice {
- hasAssigned = true
- x := reflect.New(fieldType)
- if len(vv.Bytes()) > 0 {
- err := DefaultJSONHandler.Unmarshal(vv.Bytes(), x.Interface())
- if err != nil {
- return nil, err
- }
- fieldValue.Set(x.Elem())
- }
- }
- } else if session.statement.UseCascade {
- table, err := session.engine.autoMapType(*fieldValue)
- if err != nil {
- return nil, err
- }
-
- hasAssigned = true
- if len(table.PrimaryKeys) != 1 {
- return nil, errors.New("unsupported non or composited primary key cascade")
- }
- var pk = make(core.PK, len(table.PrimaryKeys))
- pk[0], err = asKind(vv, rawValueType)
- if err != nil {
- return nil, err
- }
-
- if !isPKZero(pk) {
- // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
- // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
- // property to be fetched lazily
- structInter := reflect.New(fieldValue.Type())
- has, err := session.ID(pk).NoCascade().get(structInter.Interface())
- if err != nil {
- return nil, err
- }
- if has {
- fieldValue.Set(structInter.Elem())
- } else {
- return nil, errors.New("cascade obj is not exist")
- }
- }
- }
- case reflect.Ptr:
- // !nashtsai! TODO merge duplicated codes above
- switch fieldType {
- // following types case matching ptr's native type, therefore assign ptr directly
- case core.PtrStringType:
- if rawValueType.Kind() == reflect.String {
- x := vv.String()
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrBoolType:
- if rawValueType.Kind() == reflect.Bool {
- x := vv.Bool()
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrTimeType:
- if rawValueType == core.PtrTimeType {
- hasAssigned = true
- var x = rawValue.Interface().(time.Time)
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrFloat64Type:
- if rawValueType.Kind() == reflect.Float64 {
- x := vv.Float()
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrUint64Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = uint64(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrInt64Type:
- if rawValueType.Kind() == reflect.Int64 {
- x := vv.Int()
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrFloat32Type:
- if rawValueType.Kind() == reflect.Float64 {
- var x = float32(vv.Float())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrIntType:
- if rawValueType.Kind() == reflect.Int64 {
- var x = int(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrInt32Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = int32(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrInt8Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = int8(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrInt16Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = int16(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrUintType:
- if rawValueType.Kind() == reflect.Int64 {
- var x = uint(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.PtrUint32Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = uint32(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.Uint8Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = uint8(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.Uint16Type:
- if rawValueType.Kind() == reflect.Int64 {
- var x = uint16(vv.Int())
- hasAssigned = true
- fieldValue.Set(reflect.ValueOf(&x))
- }
- case core.Complex64Type:
- var x complex64
- if len([]byte(vv.String())) > 0 {
- err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), &x)
- if err != nil {
- return nil, err
- }
- fieldValue.Set(reflect.ValueOf(&x))
- }
- hasAssigned = true
- case core.Complex128Type:
- var x complex128
- if len([]byte(vv.String())) > 0 {
- err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), &x)
- if err != nil {
- return nil, err
- }
- fieldValue.Set(reflect.ValueOf(&x))
- }
- hasAssigned = true
- } // switch fieldType
- } // switch fieldType.Kind()
-
- // !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value
- if !hasAssigned {
- data, err := value2Bytes(&rawValue)
- if err != nil {
- return nil, err
- }
-
- if err = session.bytes2Value(col, fieldValue, data); err != nil {
- return nil, err
- }
- }
- }
- return pk, nil
-}
-
-// saveLastSQL stores executed query information
-func (session *Session) saveLastSQL(sql string, args ...interface{}) {
- session.lastSQL = sql
- session.lastSQLArgs = args
- session.engine.logSQL(sql, args...)
-}
-
-// LastSQL returns last query information
-func (session *Session) LastSQL() (string, []interface{}) {
- return session.lastSQL, session.lastSQLArgs
-}
-
-// Unscoped always disable struct tag "deleted"
-func (session *Session) Unscoped() *Session {
- session.statement.Unscoped()
- return session
-}
-
-func (session *Session) incrVersionFieldValue(fieldValue *reflect.Value) {
- switch fieldValue.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- fieldValue.SetInt(fieldValue.Int() + 1)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- fieldValue.SetUint(fieldValue.Uint() + 1)
- }
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_cols.go b/vendor/github.com/go-xorm/xorm/session_cols.go
deleted file mode 100644
index dc3befc..0000000
--- a/vendor/github.com/go-xorm/xorm/session_cols.go
+++ /dev/null
@@ -1,199 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "reflect"
- "strings"
- "time"
-
- "xorm.io/core"
-)
-
-type incrParam struct {
- colName string
- arg interface{}
-}
-
-type decrParam struct {
- colName string
- arg interface{}
-}
-
-type exprParam struct {
- colName string
- expr string
-}
-
-type columnMap []string
-
-func (m columnMap) contain(colName string) bool {
- if len(m) == 0 {
- return false
- }
-
- n := len(colName)
- for _, mk := range m {
- if len(mk) != n {
- continue
- }
- if strings.EqualFold(mk, colName) {
- return true
- }
- }
-
- return false
-}
-
-func (m *columnMap) add(colName string) bool {
- if m.contain(colName) {
- return false
- }
- *m = append(*m, colName)
- return true
-}
-
-func setColumnInt(bean interface{}, col *core.Column, t int64) {
- v, err := col.ValueOf(bean)
- if err != nil {
- return
- }
- if v.CanSet() {
- switch v.Type().Kind() {
- case reflect.Int, reflect.Int64, reflect.Int32:
- v.SetInt(t)
- case reflect.Uint, reflect.Uint64, reflect.Uint32:
- v.SetUint(uint64(t))
- }
- }
-}
-
-func setColumnTime(bean interface{}, col *core.Column, t time.Time) {
- v, err := col.ValueOf(bean)
- if err != nil {
- return
- }
- if v.CanSet() {
- switch v.Type().Kind() {
- case reflect.Struct:
- v.Set(reflect.ValueOf(t).Convert(v.Type()))
- case reflect.Int, reflect.Int64, reflect.Int32:
- v.SetInt(t.Unix())
- case reflect.Uint, reflect.Uint64, reflect.Uint32:
- v.SetUint(uint64(t.Unix()))
- }
- }
-}
-
-func getFlagForColumn(m map[string]bool, col *core.Column) (val bool, has bool) {
- if len(m) == 0 {
- return false, false
- }
-
- n := len(col.Name)
-
- for mk := range m {
- if len(mk) != n {
- continue
- }
- if strings.EqualFold(mk, col.Name) {
- return m[mk], true
- }
- }
-
- return false, false
-}
-
-func col2NewCols(columns ...string) []string {
- newColumns := make([]string, 0, len(columns))
- for _, col := range columns {
- col = strings.Replace(col, "`", "", -1)
- col = strings.Replace(col, `"`, "", -1)
- ccols := strings.Split(col, ",")
- for _, c := range ccols {
- newColumns = append(newColumns, strings.TrimSpace(c))
- }
- }
- return newColumns
-}
-
-// Incr provides a query string like "count = count + 1"
-func (session *Session) Incr(column string, arg ...interface{}) *Session {
- session.statement.Incr(column, arg...)
- return session
-}
-
-// Decr provides a query string like "count = count - 1"
-func (session *Session) Decr(column string, arg ...interface{}) *Session {
- session.statement.Decr(column, arg...)
- return session
-}
-
-// SetExpr provides a query string like "column = {expression}"
-func (session *Session) SetExpr(column string, expression string) *Session {
- session.statement.SetExpr(column, expression)
- return session
-}
-
-// Select provides some columns to special
-func (session *Session) Select(str string) *Session {
- session.statement.Select(str)
- return session
-}
-
-// Cols provides some columns to special
-func (session *Session) Cols(columns ...string) *Session {
- session.statement.Cols(columns...)
- return session
-}
-
-// AllCols ask all columns
-func (session *Session) AllCols() *Session {
- session.statement.AllCols()
- return session
-}
-
-// MustCols specify some columns must use even if they are empty
-func (session *Session) MustCols(columns ...string) *Session {
- session.statement.MustCols(columns...)
- return session
-}
-
-// UseBool automatically retrieve condition according struct, but
-// if struct has bool field, it will ignore them. So use UseBool
-// to tell system to do not ignore them.
-// If no parameters, it will use all the bool field of struct, or
-// it will use parameters's columns
-func (session *Session) UseBool(columns ...string) *Session {
- session.statement.UseBool(columns...)
- return session
-}
-
-// Distinct use for distinct columns. Caution: when you are using cache,
-// distinct will not be cached because cache system need id,
-// but distinct will not provide id
-func (session *Session) Distinct(columns ...string) *Session {
- session.statement.Distinct(columns...)
- return session
-}
-
-// Omit Only not use the parameters as select or update columns
-func (session *Session) Omit(columns ...string) *Session {
- session.statement.Omit(columns...)
- return session
-}
-
-// Nullable Set null when column is zero-value and nullable for update
-func (session *Session) Nullable(columns ...string) *Session {
- session.statement.Nullable(columns...)
- return session
-}
-
-// NoAutoTime means do not automatically give created field and updated field
-// the current time on the current session temporarily
-func (session *Session) NoAutoTime() *Session {
- session.statement.UseAutoTime = false
- return session
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_cond.go b/vendor/github.com/go-xorm/xorm/session_cond.go
deleted file mode 100644
index b16bdea..0000000
--- a/vendor/github.com/go-xorm/xorm/session_cond.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import "xorm.io/builder"
-
-// Sql provides raw sql input parameter. When you have a complex SQL statement
-// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
-//
-// Deprecated: use SQL instead.
-func (session *Session) Sql(query string, args ...interface{}) *Session {
- return session.SQL(query, args...)
-}
-
-// SQL provides raw sql input parameter. When you have a complex SQL statement
-// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
-func (session *Session) SQL(query interface{}, args ...interface{}) *Session {
- session.statement.SQL(query, args...)
- return session
-}
-
-// Where provides custom query condition.
-func (session *Session) Where(query interface{}, args ...interface{}) *Session {
- session.statement.Where(query, args...)
- return session
-}
-
-// And provides custom query condition.
-func (session *Session) And(query interface{}, args ...interface{}) *Session {
- session.statement.And(query, args...)
- return session
-}
-
-// Or provides custom query condition.
-func (session *Session) Or(query interface{}, args ...interface{}) *Session {
- session.statement.Or(query, args...)
- return session
-}
-
-// Id provides converting id as a query condition
-//
-// Deprecated: use ID instead
-func (session *Session) Id(id interface{}) *Session {
- return session.ID(id)
-}
-
-// ID provides converting id as a query condition
-func (session *Session) ID(id interface{}) *Session {
- session.statement.ID(id)
- return session
-}
-
-// In provides a query string like "id in (1, 2, 3)"
-func (session *Session) In(column string, args ...interface{}) *Session {
- session.statement.In(column, args...)
- return session
-}
-
-// NotIn provides a query string like "id in (1, 2, 3)"
-func (session *Session) NotIn(column string, args ...interface{}) *Session {
- session.statement.NotIn(column, args...)
- return session
-}
-
-// Conds returns session query conditions except auto bean conditions
-func (session *Session) Conds() builder.Cond {
- return session.statement.cond
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_context.go b/vendor/github.com/go-xorm/xorm/session_context.go
deleted file mode 100644
index 915f056..0000000
--- a/vendor/github.com/go-xorm/xorm/session_context.go
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2019 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import "context"
-
-// Context sets the context on this session
-func (session *Session) Context(ctx context.Context) *Session {
- session.ctx = ctx
- return session
-}
-
-// PingContext test if database is ok
-func (session *Session) PingContext(ctx context.Context) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
- return session.DB().PingContext(ctx)
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_convert.go b/vendor/github.com/go-xorm/xorm/session_convert.go
deleted file mode 100644
index caff5d2..0000000
--- a/vendor/github.com/go-xorm/xorm/session_convert.go
+++ /dev/null
@@ -1,661 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "database/sql/driver"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "time"
-
- "xorm.io/core"
-)
-
-func (session *Session) str2Time(col *core.Column, data string) (outTime time.Time, outErr error) {
- sdata := strings.TrimSpace(data)
- var x time.Time
- var err error
-
- var parseLoc = session.engine.DatabaseTZ
- if col.TimeZone != nil {
- parseLoc = col.TimeZone
- }
-
- if sdata == zeroTime0 || sdata == zeroTime1 {
- } else if !strings.ContainsAny(sdata, "- :") { // !nashtsai! has only found that mymysql driver is using this for time type column
- // time stamp
- sd, err := strconv.ParseInt(sdata, 10, 64)
- if err == nil {
- x = time.Unix(sd, 0)
- //session.engine.logger.Debugf("time(0) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- } else {
- //session.engine.logger.Debugf("time(0) err key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- }
- } else if len(sdata) > 19 && strings.Contains(sdata, "-") {
- x, err = time.ParseInLocation(time.RFC3339Nano, sdata, parseLoc)
- session.engine.logger.Debugf("time(1) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- if err != nil {
- x, err = time.ParseInLocation("2006-01-02 15:04:05.999999999", sdata, parseLoc)
- //session.engine.logger.Debugf("time(2) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- }
- if err != nil {
- x, err = time.ParseInLocation("2006-01-02 15:04:05.9999999 Z07:00", sdata, parseLoc)
- //session.engine.logger.Debugf("time(3) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- }
- } else if len(sdata) == 19 && strings.Contains(sdata, "-") {
- x, err = time.ParseInLocation("2006-01-02 15:04:05", sdata, parseLoc)
- //session.engine.logger.Debugf("time(4) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- } else if len(sdata) == 10 && sdata[4] == '-' && sdata[7] == '-' {
- x, err = time.ParseInLocation("2006-01-02", sdata, parseLoc)
- //session.engine.logger.Debugf("time(5) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- } else if col.SQLType.Name == core.Time {
- if strings.Contains(sdata, " ") {
- ssd := strings.Split(sdata, " ")
- sdata = ssd[1]
- }
-
- sdata = strings.TrimSpace(sdata)
- if session.engine.dialect.DBType() == core.MYSQL && len(sdata) > 8 {
- sdata = sdata[len(sdata)-8:]
- }
-
- st := fmt.Sprintf("2006-01-02 %v", sdata)
- x, err = time.ParseInLocation("2006-01-02 15:04:05", st, parseLoc)
- //session.engine.logger.Debugf("time(6) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
- } else {
- outErr = fmt.Errorf("unsupported time format %v", sdata)
- return
- }
- if err != nil {
- outErr = fmt.Errorf("unsupported time format %v: %v", sdata, err)
- return
- }
- outTime = x.In(session.engine.TZLocation)
- return
-}
-
-func (session *Session) byte2Time(col *core.Column, data []byte) (outTime time.Time, outErr error) {
- return session.str2Time(col, string(data))
-}
-
-// convert a db data([]byte) to a field value
-func (session *Session) bytes2Value(col *core.Column, fieldValue *reflect.Value, data []byte) error {
- if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
- return structConvert.FromDB(data)
- }
-
- if structConvert, ok := fieldValue.Interface().(core.Conversion); ok {
- return structConvert.FromDB(data)
- }
-
- var v interface{}
- key := col.Name
- fieldType := fieldValue.Type()
-
- switch fieldType.Kind() {
- case reflect.Complex64, reflect.Complex128:
- x := reflect.New(fieldType)
- if len(data) > 0 {
- err := DefaultJSONHandler.Unmarshal(data, x.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return err
- }
- fieldValue.Set(x.Elem())
- }
- case reflect.Slice, reflect.Array, reflect.Map:
- v = data
- t := fieldType.Elem()
- k := t.Kind()
- if col.SQLType.IsText() {
- x := reflect.New(fieldType)
- if len(data) > 0 {
- err := DefaultJSONHandler.Unmarshal(data, x.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return err
- }
- fieldValue.Set(x.Elem())
- }
- } else if col.SQLType.IsBlob() {
- if k == reflect.Uint8 {
- fieldValue.Set(reflect.ValueOf(v))
- } else {
- x := reflect.New(fieldType)
- if len(data) > 0 {
- err := DefaultJSONHandler.Unmarshal(data, x.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return err
- }
- fieldValue.Set(x.Elem())
- }
- }
- } else {
- return ErrUnSupportedType
- }
- case reflect.String:
- fieldValue.SetString(string(data))
- case reflect.Bool:
- v, err := asBool(data)
- if err != nil {
- return fmt.Errorf("arg %v as bool: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(v))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- sdata := string(data)
- var x int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- session.engine.dialect.DBType() == core.MYSQL { // !nashtsai! TODO dialect needs to provide conversion interface API
- if len(data) == 1 {
- x = int64(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x, err = strconv.ParseInt(sdata, 16, 64)
- } else if strings.HasPrefix(sdata, "0") {
- x, err = strconv.ParseInt(sdata, 8, 64)
- } else if strings.EqualFold(sdata, "true") {
- x = 1
- } else if strings.EqualFold(sdata, "false") {
- x = 0
- } else {
- x, err = strconv.ParseInt(sdata, 10, 64)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.SetInt(x)
- case reflect.Float32, reflect.Float64:
- x, err := strconv.ParseFloat(string(data), 64)
- if err != nil {
- return fmt.Errorf("arg %v as float64: %s", key, err.Error())
- }
- fieldValue.SetFloat(x)
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- x, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.SetUint(x)
- //Currently only support Time type
- case reflect.Struct:
- // !! 增加支持sql.Scanner接口的结构,如sql.NullString
- if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
- if err := nulVal.Scan(data); err != nil {
- return fmt.Errorf("sql.Scan(%v) failed: %s ", data, err.Error())
- }
- } else {
- if fieldType.ConvertibleTo(core.TimeType) {
- x, err := session.byte2Time(col, data)
- if err != nil {
- return err
- }
- v = x
- fieldValue.Set(reflect.ValueOf(v).Convert(fieldType))
- } else if session.statement.UseCascade {
- table, err := session.engine.autoMapType(*fieldValue)
- if err != nil {
- return err
- }
-
- // TODO: current only support 1 primary key
- if len(table.PrimaryKeys) > 1 {
- return errors.New("unsupported composited primary key cascade")
- }
-
- var pk = make(core.PK, len(table.PrimaryKeys))
- rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
- pk[0], err = str2PK(string(data), rawValueType)
- if err != nil {
- return err
- }
-
- if !isPKZero(pk) {
- // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
- // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
- // property to be fetched lazily
- structInter := reflect.New(fieldValue.Type())
- has, err := session.ID(pk).NoCascade().get(structInter.Interface())
- if err != nil {
- return err
- }
- if has {
- v = structInter.Elem().Interface()
- fieldValue.Set(reflect.ValueOf(v))
- } else {
- return errors.New("cascade obj is not exist")
- }
- }
- }
- }
- case reflect.Ptr:
- // !nashtsai! TODO merge duplicated codes above
- //typeStr := fieldType.String()
- switch fieldType.Elem().Kind() {
- // case "*string":
- case core.StringType.Kind():
- x := string(data)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*bool":
- case core.BoolType.Kind():
- d := string(data)
- v, err := strconv.ParseBool(d)
- if err != nil {
- return fmt.Errorf("arg %v as bool: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&v).Convert(fieldType))
- // case "*complex64":
- case core.Complex64Type.Kind():
- var x complex64
- if len(data) > 0 {
- err := DefaultJSONHandler.Unmarshal(data, &x)
- if err != nil {
- session.engine.logger.Error(err)
- return err
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- }
- // case "*complex128":
- case core.Complex128Type.Kind():
- var x complex128
- if len(data) > 0 {
- err := DefaultJSONHandler.Unmarshal(data, &x)
- if err != nil {
- session.engine.logger.Error(err)
- return err
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- }
- // case "*float64":
- case core.Float64Type.Kind():
- x, err := strconv.ParseFloat(string(data), 64)
- if err != nil {
- return fmt.Errorf("arg %v as float64: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*float32":
- case core.Float32Type.Kind():
- var x float32
- x1, err := strconv.ParseFloat(string(data), 32)
- if err != nil {
- return fmt.Errorf("arg %v as float32: %s", key, err.Error())
- }
- x = float32(x1)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*uint64":
- case core.Uint64Type.Kind():
- var x uint64
- x, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*uint":
- case core.UintType.Kind():
- var x uint
- x1, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- x = uint(x1)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*uint32":
- case core.Uint32Type.Kind():
- var x uint32
- x1, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- x = uint32(x1)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*uint8":
- case core.Uint8Type.Kind():
- var x uint8
- x1, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- x = uint8(x1)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*uint16":
- case core.Uint16Type.Kind():
- var x uint16
- x1, err := strconv.ParseUint(string(data), 10, 64)
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- x = uint16(x1)
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*int64":
- case core.Int64Type.Kind():
- sdata := string(data)
- var x int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- strings.Contains(session.engine.DriverName(), "mysql") {
- if len(data) == 1 {
- x = int64(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x, err = strconv.ParseInt(sdata, 16, 64)
- } else if strings.HasPrefix(sdata, "0") {
- x, err = strconv.ParseInt(sdata, 8, 64)
- } else {
- x, err = strconv.ParseInt(sdata, 10, 64)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*int":
- case core.IntType.Kind():
- sdata := string(data)
- var x int
- var x1 int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- strings.Contains(session.engine.DriverName(), "mysql") {
- if len(data) == 1 {
- x = int(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x1, err = strconv.ParseInt(sdata, 16, 64)
- x = int(x1)
- } else if strings.HasPrefix(sdata, "0") {
- x1, err = strconv.ParseInt(sdata, 8, 64)
- x = int(x1)
- } else {
- x1, err = strconv.ParseInt(sdata, 10, 64)
- x = int(x1)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*int32":
- case core.Int32Type.Kind():
- sdata := string(data)
- var x int32
- var x1 int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- session.engine.dialect.DBType() == core.MYSQL {
- if len(data) == 1 {
- x = int32(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x1, err = strconv.ParseInt(sdata, 16, 64)
- x = int32(x1)
- } else if strings.HasPrefix(sdata, "0") {
- x1, err = strconv.ParseInt(sdata, 8, 64)
- x = int32(x1)
- } else {
- x1, err = strconv.ParseInt(sdata, 10, 64)
- x = int32(x1)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*int8":
- case core.Int8Type.Kind():
- sdata := string(data)
- var x int8
- var x1 int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- strings.Contains(session.engine.DriverName(), "mysql") {
- if len(data) == 1 {
- x = int8(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x1, err = strconv.ParseInt(sdata, 16, 64)
- x = int8(x1)
- } else if strings.HasPrefix(sdata, "0") {
- x1, err = strconv.ParseInt(sdata, 8, 64)
- x = int8(x1)
- } else {
- x1, err = strconv.ParseInt(sdata, 10, 64)
- x = int8(x1)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*int16":
- case core.Int16Type.Kind():
- sdata := string(data)
- var x int16
- var x1 int64
- var err error
- // for mysql, when use bit, it returned \x01
- if col.SQLType.Name == core.Bit &&
- strings.Contains(session.engine.DriverName(), "mysql") {
- if len(data) == 1 {
- x = int16(data[0])
- } else {
- x = 0
- }
- } else if strings.HasPrefix(sdata, "0x") {
- x1, err = strconv.ParseInt(sdata, 16, 64)
- x = int16(x1)
- } else if strings.HasPrefix(sdata, "0") {
- x1, err = strconv.ParseInt(sdata, 8, 64)
- x = int16(x1)
- } else {
- x1, err = strconv.ParseInt(sdata, 10, 64)
- x = int16(x1)
- }
- if err != nil {
- return fmt.Errorf("arg %v as int: %s", key, err.Error())
- }
- fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
- // case "*SomeStruct":
- case reflect.Struct:
- switch fieldType {
- // case "*.time.Time":
- case core.PtrTimeType:
- x, err := session.byte2Time(col, data)
- if err != nil {
- return err
- }
- v = x
- fieldValue.Set(reflect.ValueOf(&x))
- default:
- if session.statement.UseCascade {
- structInter := reflect.New(fieldType.Elem())
- table, err := session.engine.autoMapType(structInter.Elem())
- if err != nil {
- return err
- }
-
- if len(table.PrimaryKeys) > 1 {
- return errors.New("unsupported composited primary key cascade")
- }
-
- var pk = make(core.PK, len(table.PrimaryKeys))
- rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
- pk[0], err = str2PK(string(data), rawValueType)
- if err != nil {
- return err
- }
-
- if !isPKZero(pk) {
- // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
- // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
- // property to be fetched lazily
- has, err := session.ID(pk).NoCascade().get(structInter.Interface())
- if err != nil {
- return err
- }
- if has {
- v = structInter.Interface()
- fieldValue.Set(reflect.ValueOf(v))
- } else {
- return errors.New("cascade obj is not exist")
- }
- }
- } else {
- return fmt.Errorf("unsupported struct type in Scan: %s", fieldValue.Type().String())
- }
- }
- default:
- return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
- }
- default:
- return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
- }
-
- return nil
-}
-
-// convert a field value of a struct to interface for put into db
-func (session *Session) value2Interface(col *core.Column, fieldValue reflect.Value) (interface{}, error) {
- if fieldValue.CanAddr() {
- if fieldConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
- data, err := fieldConvert.ToDB()
- if err != nil {
- return 0, err
- }
- if col.SQLType.IsBlob() {
- return data, nil
- }
- return string(data), nil
- }
- }
-
- if fieldConvert, ok := fieldValue.Interface().(core.Conversion); ok {
- data, err := fieldConvert.ToDB()
- if err != nil {
- return 0, err
- }
- if col.SQLType.IsBlob() {
- return data, nil
- }
- return string(data), nil
- }
-
- fieldType := fieldValue.Type()
- k := fieldType.Kind()
- if k == reflect.Ptr {
- if fieldValue.IsNil() {
- return nil, nil
- } else if !fieldValue.IsValid() {
- session.engine.logger.Warn("the field[", col.FieldName, "] is invalid")
- return nil, nil
- } else {
- // !nashtsai! deference pointer type to instance type
- fieldValue = fieldValue.Elem()
- fieldType = fieldValue.Type()
- k = fieldType.Kind()
- }
- }
-
- switch k {
- case reflect.Bool:
- return fieldValue.Bool(), nil
- case reflect.String:
- return fieldValue.String(), nil
- case reflect.Struct:
- if fieldType.ConvertibleTo(core.TimeType) {
- t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
- tf := session.engine.formatColTime(col, t)
- return tf, nil
- }
-
- if !col.SQLType.IsJson() {
- // !! 增加支持driver.Valuer接口的结构,如sql.NullString
- if v, ok := fieldValue.Interface().(driver.Valuer); ok {
- return v.Value()
- }
-
- fieldTable, err := session.engine.autoMapType(fieldValue)
- if err != nil {
- return nil, err
- }
- if len(fieldTable.PrimaryKeys) == 1 {
- pkField := reflect.Indirect(fieldValue).FieldByName(fieldTable.PKColumns()[0].FieldName)
- return pkField.Interface(), nil
- }
- return 0, fmt.Errorf("no primary key for col %v", col.Name)
- }
-
- if col.SQLType.IsText() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return 0, err
- }
- return string(bytes), nil
- } else if col.SQLType.IsBlob() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return 0, err
- }
- return bytes, nil
- }
- return nil, fmt.Errorf("Unsupported type %v", fieldValue.Type())
- case reflect.Complex64, reflect.Complex128:
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return 0, err
- }
- return string(bytes), nil
- case reflect.Array, reflect.Slice, reflect.Map:
- if !fieldValue.IsValid() {
- return fieldValue.Interface(), nil
- }
-
- if col.SQLType.IsText() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return 0, err
- }
- return string(bytes), nil
- } else if col.SQLType.IsBlob() {
- var bytes []byte
- var err error
- if (k == reflect.Slice) &&
- (fieldValue.Type().Elem().Kind() == reflect.Uint8) {
- bytes = fieldValue.Bytes()
- } else {
- bytes, err = DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- session.engine.logger.Error(err)
- return 0, err
- }
- }
- return bytes, nil
- }
- return nil, ErrUnSupportedType
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- return int64(fieldValue.Uint()), nil
- default:
- return fieldValue.Interface(), nil
- }
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_delete.go b/vendor/github.com/go-xorm/xorm/session_delete.go
deleted file mode 100644
index 675d4d8..0000000
--- a/vendor/github.com/go-xorm/xorm/session_delete.go
+++ /dev/null
@@ -1,244 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "strconv"
-
- "xorm.io/core"
-)
-
-func (session *Session) cacheDelete(table *core.Table, tableName, sqlStr string, args ...interface{}) error {
- if table == nil ||
- session.tx != nil {
- return ErrCacheFailed
- }
-
- for _, filter := range session.engine.dialect.Filters() {
- sqlStr = filter.Do(sqlStr, session.engine.dialect, table)
- }
-
- newsql := session.statement.convertIDSQL(sqlStr)
- if newsql == "" {
- return ErrCacheFailed
- }
-
- cacher := session.engine.getCacher(tableName)
- pkColumns := table.PKColumns()
- ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
- if err != nil {
- resultsSlice, err := session.queryBytes(newsql, args...)
- if err != nil {
- return err
- }
- ids = make([]core.PK, 0)
- if len(resultsSlice) > 0 {
- for _, data := range resultsSlice {
- var id int64
- var pk core.PK = make([]interface{}, 0)
- for _, col := range pkColumns {
- if v, ok := data[col.Name]; !ok {
- return errors.New("no id")
- } else if col.SQLType.IsText() {
- pk = append(pk, string(v))
- } else if col.SQLType.IsNumeric() {
- id, err = strconv.ParseInt(string(v), 10, 64)
- if err != nil {
- return err
- }
- pk = append(pk, id)
- } else {
- return errors.New("not supported primary key type")
- }
- }
- ids = append(ids, pk)
- }
- }
- }
-
- for _, id := range ids {
- session.engine.logger.Debug("[cacheDelete] delete cache obj:", tableName, id)
- sid, err := id.ToString()
- if err != nil {
- return err
- }
- cacher.DelBean(tableName, sid)
- }
- session.engine.logger.Debug("[cacheDelete] clear cache table:", tableName)
- cacher.ClearIds(tableName)
- return nil
-}
-
-// Delete records, bean's non-empty fields are conditions
-func (session *Session) Delete(bean interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- if session.statement.lastError != nil {
- return 0, session.statement.lastError
- }
-
- if err := session.statement.setRefBean(bean); err != nil {
- return 0, err
- }
-
- // handle before delete processors
- for _, closure := range session.beforeClosures {
- closure(bean)
- }
- cleanupProcessorsClosures(&session.beforeClosures)
-
- if processor, ok := interface{}(bean).(BeforeDeleteProcessor); ok {
- processor.BeforeDelete()
- }
-
- condSQL, condArgs, err := session.statement.genConds(bean)
- if err != nil {
- return 0, err
- }
- if len(condSQL) == 0 && session.statement.LimitN == 0 {
- return 0, ErrNeedDeletedCond
- }
-
- var tableNameNoQuote = session.statement.TableName()
- var tableName = session.engine.Quote(tableNameNoQuote)
- var table = session.statement.RefTable
- var deleteSQL string
- if len(condSQL) > 0 {
- deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condSQL)
- } else {
- deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName)
- }
-
- var orderSQL string
- if len(session.statement.OrderStr) > 0 {
- orderSQL += fmt.Sprintf(" ORDER BY %s", session.statement.OrderStr)
- }
- if session.statement.LimitN > 0 {
- orderSQL += fmt.Sprintf(" LIMIT %d", session.statement.LimitN)
- }
-
- if len(orderSQL) > 0 {
- switch session.engine.dialect.DBType() {
- case core.POSTGRES:
- inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
- if len(condSQL) > 0 {
- deleteSQL += " AND " + inSQL
- } else {
- deleteSQL += " WHERE " + inSQL
- }
- case core.SQLITE:
- inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
- if len(condSQL) > 0 {
- deleteSQL += " AND " + inSQL
- } else {
- deleteSQL += " WHERE " + inSQL
- }
- // TODO: how to handle delete limit on mssql?
- case core.MSSQL:
- return 0, ErrNotImplemented
- default:
- deleteSQL += orderSQL
- }
- }
-
- var realSQL string
- argsForCache := make([]interface{}, 0, len(condArgs)*2)
- if session.statement.unscoped || table.DeletedColumn() == nil { // tag "deleted" is disabled
- realSQL = deleteSQL
- copy(argsForCache, condArgs)
- argsForCache = append(condArgs, argsForCache...)
- } else {
- // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for cache.
- copy(argsForCache, condArgs)
- argsForCache = append(condArgs, argsForCache...)
-
- deletedColumn := table.DeletedColumn()
- realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v",
- session.engine.Quote(session.statement.TableName()),
- session.engine.Quote(deletedColumn.Name),
- condSQL)
-
- if len(orderSQL) > 0 {
- switch session.engine.dialect.DBType() {
- case core.POSTGRES:
- inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
- if len(condSQL) > 0 {
- realSQL += " AND " + inSQL
- } else {
- realSQL += " WHERE " + inSQL
- }
- case core.SQLITE:
- inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
- if len(condSQL) > 0 {
- realSQL += " AND " + inSQL
- } else {
- realSQL += " WHERE " + inSQL
- }
- // TODO: how to handle delete limit on mssql?
- case core.MSSQL:
- return 0, ErrNotImplemented
- default:
- realSQL += orderSQL
- }
- }
-
- // !oinume! Insert nowTime to the head of session.statement.Params
- condArgs = append(condArgs, "")
- paramsLen := len(condArgs)
- copy(condArgs[1:paramsLen], condArgs[0:paramsLen-1])
-
- val, t := session.engine.nowTime(deletedColumn)
- condArgs[0] = val
-
- var colName = deletedColumn.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- }
-
- if cacher := session.engine.getCacher(tableNameNoQuote); cacher != nil && session.statement.UseCache {
- session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
- }
-
- session.statement.RefTable = table
- res, err := session.exec(realSQL, condArgs...)
- if err != nil {
- return 0, err
- }
-
- // handle after delete processors
- if session.isAutoCommit {
- for _, closure := range session.afterClosures {
- closure(bean)
- }
- if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
- processor.AfterDelete()
- }
- } else {
- lenAfterClosures := len(session.afterClosures)
- if lenAfterClosures > 0 {
- if value, has := session.afterDeleteBeans[bean]; has && value != nil {
- *value = append(*value, session.afterClosures...)
- } else {
- afterClosures := make([]func(interface{}), lenAfterClosures)
- copy(afterClosures, session.afterClosures)
- session.afterDeleteBeans[bean] = &afterClosures
- }
- } else {
- if _, ok := interface{}(bean).(AfterDeleteProcessor); ok {
- session.afterDeleteBeans[bean] = nil
- }
- }
- }
- cleanupProcessorsClosures(&session.afterClosures)
- // --
-
- return res.RowsAffected()
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_exist.go b/vendor/github.com/go-xorm/xorm/session_exist.go
deleted file mode 100644
index 660cc47..0000000
--- a/vendor/github.com/go-xorm/xorm/session_exist.go
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "reflect"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-// Exist returns true if the record exist otherwise return false
-func (session *Session) Exist(bean ...interface{}) (bool, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- if session.statement.lastError != nil {
- return false, session.statement.lastError
- }
-
- var sqlStr string
- var args []interface{}
- var err error
-
- if session.statement.RawSQL == "" {
- if len(bean) == 0 {
- tableName := session.statement.TableName()
- if len(tableName) <= 0 {
- return false, ErrTableNotFound
- }
-
- tableName = session.statement.Engine.Quote(tableName)
-
- if session.statement.cond.IsValid() {
- condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
- if err != nil {
- return false, err
- }
-
- if session.engine.dialect.DBType() == core.MSSQL {
- sqlStr = fmt.Sprintf("SELECT TOP 1 * FROM %s WHERE %s", tableName, condSQL)
- } else if session.engine.dialect.DBType() == core.ORACLE {
- sqlStr = fmt.Sprintf("SELECT * FROM %s WHERE (%s) AND ROWNUM=1", tableName, condSQL)
- } else {
- sqlStr = fmt.Sprintf("SELECT * FROM %s WHERE %s LIMIT 1", tableName, condSQL)
- }
- args = condArgs
- } else {
- if session.engine.dialect.DBType() == core.MSSQL {
- sqlStr = fmt.Sprintf("SELECT TOP 1 * FROM %s", tableName)
- } else if session.engine.dialect.DBType() == core.ORACLE {
- sqlStr = fmt.Sprintf("SELECT * FROM %s WHERE ROWNUM=1", tableName)
- } else {
- sqlStr = fmt.Sprintf("SELECT * FROM %s LIMIT 1", tableName)
- }
- args = []interface{}{}
- }
- } else {
- beanValue := reflect.ValueOf(bean[0])
- if beanValue.Kind() != reflect.Ptr {
- return false, errors.New("needs a pointer")
- }
-
- if beanValue.Elem().Kind() == reflect.Struct {
- if err := session.statement.setRefBean(bean[0]); err != nil {
- return false, err
- }
- }
-
- if len(session.statement.TableName()) <= 0 {
- return false, ErrTableNotFound
- }
- session.statement.Limit(1)
- sqlStr, args, err = session.statement.genGetSQL(bean[0])
- if err != nil {
- return false, err
- }
- }
- } else {
- sqlStr = session.statement.RawSQL
- args = session.statement.RawParams
- }
-
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- return rows.Next(), nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_find.go b/vendor/github.com/go-xorm/xorm/session_find.go
deleted file mode 100644
index d3fc0d3..0000000
--- a/vendor/github.com/go-xorm/xorm/session_find.go
+++ /dev/null
@@ -1,503 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "reflect"
- "strings"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-const (
- tpStruct = iota
- tpNonStruct
-)
-
-// Find retrieve records from table, condiBeans's non-empty fields
-// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
-// map[int64]*Struct
-func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
- return session.find(rowsSlicePtr, condiBean...)
-}
-
-// FindAndCount find the results and also return the counts
-func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- session.autoResetStatement = false
- err := session.find(rowsSlicePtr, condiBean...)
- if err != nil {
- return 0, err
- }
-
- sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
- if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
- return 0, errors.New("needs a pointer to a slice or a map")
- }
-
- sliceElementType := sliceValue.Type().Elem()
- if sliceElementType.Kind() == reflect.Ptr {
- sliceElementType = sliceElementType.Elem()
- }
- session.autoResetStatement = true
-
- if session.statement.selectStr != "" {
- session.statement.selectStr = ""
- }
- if session.statement.OrderStr != "" {
- session.statement.OrderStr = ""
- }
-
- return session.Count(reflect.New(sliceElementType).Interface())
-}
-
-func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
- if session.statement.lastError != nil {
- return session.statement.lastError
- }
-
- sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
- if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
- return errors.New("needs a pointer to a slice or a map")
- }
-
- sliceElementType := sliceValue.Type().Elem()
-
- var tp = tpStruct
- if session.statement.RefTable == nil {
- if sliceElementType.Kind() == reflect.Ptr {
- if sliceElementType.Elem().Kind() == reflect.Struct {
- pv := reflect.New(sliceElementType.Elem())
- if err := session.statement.setRefValue(pv); err != nil {
- return err
- }
- } else {
- tp = tpNonStruct
- }
- } else if sliceElementType.Kind() == reflect.Struct {
- pv := reflect.New(sliceElementType)
- if err := session.statement.setRefValue(pv); err != nil {
- return err
- }
- } else {
- tp = tpNonStruct
- }
- }
-
- var table = session.statement.RefTable
-
- var addedTableName = (len(session.statement.JoinStr) > 0)
- var autoCond builder.Cond
- if tp == tpStruct {
- if !session.statement.noAutoCondition && len(condiBean) > 0 {
- var err error
- autoCond, err = session.statement.buildConds(table, condiBean[0], true, true, false, true, addedTableName)
- if err != nil {
- return err
- }
- } else {
- // !oinume! Add " IS NULL" to WHERE whatever condiBean is given.
- // See https://github.com/go-xorm/xorm/issues/179
- if col := table.DeletedColumn(); col != nil && !session.statement.unscoped { // tag "deleted" is enabled
- var colName = session.engine.Quote(col.Name)
- if addedTableName {
- var nm = session.statement.TableName()
- if len(session.statement.TableAlias) > 0 {
- nm = session.statement.TableAlias
- }
- colName = session.engine.Quote(nm) + "." + colName
- }
-
- autoCond = session.engine.CondDeleted(colName)
- }
- }
- }
-
- var sqlStr string
- var args []interface{}
- var err error
- if session.statement.RawSQL == "" {
- if len(session.statement.TableName()) <= 0 {
- return ErrTableNotFound
- }
-
- var columnStr = session.statement.ColumnStr
- if len(session.statement.selectStr) > 0 {
- columnStr = session.statement.selectStr
- } else {
- if session.statement.JoinStr == "" {
- if columnStr == "" {
- if session.statement.GroupByStr != "" {
- columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
- } else {
- columnStr = session.statement.genColumnStr()
- }
- }
- } else {
- if columnStr == "" {
- if session.statement.GroupByStr != "" {
- columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
- } else {
- columnStr = "*"
- }
- }
- }
- if columnStr == "" {
- columnStr = "*"
- }
- }
-
- session.statement.cond = session.statement.cond.And(autoCond)
- condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
- if err != nil {
- return err
- }
-
- args = append(session.statement.joinArgs, condArgs...)
- sqlStr, err = session.statement.genSelectSQL(columnStr, condSQL, true, true)
- if err != nil {
- return err
- }
- // for mssql and use limit
- qs := strings.Count(sqlStr, "?")
- if len(args)*2 == qs {
- args = append(args, args...)
- }
- } else {
- sqlStr = session.statement.RawSQL
- args = session.statement.RawParams
- }
-
- if session.canCache() {
- if cacher := session.engine.getCacher(session.statement.TableName()); cacher != nil &&
- !session.statement.IsDistinct &&
- !session.statement.unscoped {
- err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...)
- if err != ErrCacheFailed {
- return err
- }
- err = nil // !nashtsai! reset err to nil for ErrCacheFailed
- session.engine.logger.Warn("Cache Find Failed")
- }
- }
-
- return session.noCacheFind(table, sliceValue, sqlStr, args...)
-}
-
-func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Value, sqlStr string, args ...interface{}) error {
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- fields, err := rows.Columns()
- if err != nil {
- return err
- }
-
- var newElemFunc func(fields []string) reflect.Value
- elemType := containerValue.Type().Elem()
- var isPointer bool
- if elemType.Kind() == reflect.Ptr {
- isPointer = true
- elemType = elemType.Elem()
- }
- if elemType.Kind() == reflect.Ptr {
- return errors.New("pointer to pointer is not supported")
- }
-
- newElemFunc = func(fields []string) reflect.Value {
- switch elemType.Kind() {
- case reflect.Slice:
- slice := reflect.MakeSlice(elemType, len(fields), len(fields))
- x := reflect.New(slice.Type())
- x.Elem().Set(slice)
- return x
- case reflect.Map:
- mp := reflect.MakeMap(elemType)
- x := reflect.New(mp.Type())
- x.Elem().Set(mp)
- return x
- }
- return reflect.New(elemType)
- }
-
- var containerValueSetFunc func(*reflect.Value, core.PK) error
-
- if containerValue.Kind() == reflect.Slice {
- containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
- if isPointer {
- containerValue.Set(reflect.Append(containerValue, newValue.Elem().Addr()))
- } else {
- containerValue.Set(reflect.Append(containerValue, newValue.Elem()))
- }
- return nil
- }
- } else {
- keyType := containerValue.Type().Key()
- if len(table.PrimaryKeys) == 0 {
- return errors.New("don't support multiple primary key's map has non-slice key type")
- }
- if len(table.PrimaryKeys) > 1 && keyType.Kind() != reflect.Slice {
- return errors.New("don't support multiple primary key's map has non-slice key type")
- }
-
- containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
- keyValue := reflect.New(keyType)
- err := convertPKToValue(table, keyValue.Interface(), pk)
- if err != nil {
- return err
- }
- if isPointer {
- containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem().Addr())
- } else {
- containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem())
- }
- return nil
- }
- }
-
- if elemType.Kind() == reflect.Struct {
- var newValue = newElemFunc(fields)
- dataStruct := rValue(newValue.Interface())
- tb, err := session.engine.autoMapType(dataStruct)
- if err != nil {
- return err
- }
- err = session.rows2Beans(rows, fields, tb, newElemFunc, containerValueSetFunc)
- rows.Close()
- if err != nil {
- return err
- }
- return session.executeProcessors()
- }
-
- for rows.Next() {
- var newValue = newElemFunc(fields)
- bean := newValue.Interface()
-
- switch elemType.Kind() {
- case reflect.Slice:
- err = rows.ScanSlice(bean)
- case reflect.Map:
- err = rows.ScanMap(bean)
- default:
- err = rows.Scan(bean)
- }
-
- if err != nil {
- return err
- }
-
- if err := containerValueSetFunc(&newValue, nil); err != nil {
- return err
- }
- }
- return nil
-}
-
-func convertPKToValue(table *core.Table, dst interface{}, pk core.PK) error {
- cols := table.PKColumns()
- if len(cols) == 1 {
- return convertAssign(dst, pk[0])
- }
-
- dst = pk
- return nil
-}
-
-func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr interface{}, args ...interface{}) (err error) {
- if !session.canCache() ||
- indexNoCase(sqlStr, "having") != -1 ||
- indexNoCase(sqlStr, "group by") != -1 {
- return ErrCacheFailed
- }
-
- tableName := session.statement.TableName()
- cacher := session.engine.getCacher(tableName)
- if cacher == nil {
- return nil
- }
-
- for _, filter := range session.engine.dialect.Filters() {
- sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
- }
-
- newsql := session.statement.convertIDSQL(sqlStr)
- if newsql == "" {
- return ErrCacheFailed
- }
-
- table := session.statement.RefTable
- ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
- if err != nil {
- rows, err := session.queryRows(newsql, args...)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- var i int
- ids = make([]core.PK, 0)
- for rows.Next() {
- i++
- if i > 500 {
- session.engine.logger.Debug("[cacheFind] ids length > 500, no cache")
- return ErrCacheFailed
- }
- var res = make([]string, len(table.PrimaryKeys))
- err = rows.ScanSlice(&res)
- if err != nil {
- return err
- }
- var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
- for i, col := range table.PKColumns() {
- pk[i], err = session.engine.idTypeAssertion(col, res[i])
- if err != nil {
- return err
- }
- }
-
- ids = append(ids, pk)
- }
-
- session.engine.logger.Debug("[cacheFind] cache sql:", ids, tableName, sqlStr, newsql, args)
- err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
- if err != nil {
- return err
- }
- } else {
- session.engine.logger.Debug("[cacheFind] cache hit sql:", tableName, sqlStr, newsql, args)
- }
-
- sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
-
- ididxes := make(map[string]int)
- var ides []core.PK
- var temps = make([]interface{}, len(ids))
-
- for idx, id := range ids {
- sid, err := id.ToString()
- if err != nil {
- return err
- }
- bean := cacher.GetBean(tableName, sid)
- if bean == nil || reflect.ValueOf(bean).Elem().Type() != t {
- ides = append(ides, id)
- ididxes[sid] = idx
- } else {
- session.engine.logger.Debug("[cacheFind] cache hit bean:", tableName, id, bean)
-
- pk := session.engine.IdOf(bean)
- xid, err := pk.ToString()
- if err != nil {
- return err
- }
-
- if sid != xid {
- session.engine.logger.Error("[cacheFind] error cache", xid, sid, bean)
- return ErrCacheFailed
- }
- temps[idx] = bean
- }
- }
-
- if len(ides) > 0 {
- slices := reflect.New(reflect.SliceOf(t))
- beans := slices.Interface()
-
- if len(table.PrimaryKeys) == 1 {
- ff := make([]interface{}, 0, len(ides))
- for _, ie := range ides {
- ff = append(ff, ie[0])
- }
-
- session.In("`"+table.PrimaryKeys[0]+"`", ff...)
- } else {
- for _, ie := range ides {
- cond := builder.NewCond()
- for i, name := range table.PrimaryKeys {
- cond = cond.And(builder.Eq{"`" + name + "`": ie[i]})
- }
- session.Or(cond)
- }
- }
-
- err = session.NoCache().Table(tableName).find(beans)
- if err != nil {
- return err
- }
-
- vs := reflect.Indirect(reflect.ValueOf(beans))
- for i := 0; i < vs.Len(); i++ {
- rv := vs.Index(i)
- if rv.Kind() != reflect.Ptr {
- rv = rv.Addr()
- }
- id, err := session.engine.idOfV(rv)
- if err != nil {
- return err
- }
- sid, err := id.ToString()
- if err != nil {
- return err
- }
-
- bean := rv.Interface()
- temps[ididxes[sid]] = bean
- session.engine.logger.Debug("[cacheFind] cache bean:", tableName, id, bean, temps)
- cacher.PutBean(tableName, sid, bean)
- }
- }
-
- for j := 0; j < len(temps); j++ {
- bean := temps[j]
- if bean == nil {
- session.engine.logger.Warn("[cacheFind] cache no hit:", tableName, ids[j], temps)
- // return errors.New("cache error") // !nashtsai! no need to return error, but continue instead
- continue
- }
- if sliceValue.Kind() == reflect.Slice {
- if t.Kind() == reflect.Ptr {
- sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(bean)))
- } else {
- sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean))))
- }
- } else if sliceValue.Kind() == reflect.Map {
- var key = ids[j]
- keyType := sliceValue.Type().Key()
- var ikey interface{}
- if len(key) == 1 {
- ikey, err = str2PK(fmt.Sprintf("%v", key[0]), keyType)
- if err != nil {
- return err
- }
- } else {
- if keyType.Kind() != reflect.Slice {
- return errors.New("table have multiple primary keys, key is not core.PK or slice")
- }
- ikey = key
- }
-
- if t.Kind() == reflect.Ptr {
- sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean))
- } else {
- sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean)))
- }
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_get.go b/vendor/github.com/go-xorm/xorm/session_get.go
deleted file mode 100644
index a38707c..0000000
--- a/vendor/github.com/go-xorm/xorm/session_get.go
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "errors"
- "fmt"
- "reflect"
- "strconv"
-
- "xorm.io/core"
-)
-
-// Get retrieve one record from database, bean's non-empty fields
-// will be as conditions
-func (session *Session) Get(bean interface{}) (bool, error) {
- if session.isAutoClose {
- defer session.Close()
- }
- return session.get(bean)
-}
-
-func (session *Session) get(bean interface{}) (bool, error) {
- if session.statement.lastError != nil {
- return false, session.statement.lastError
- }
-
- beanValue := reflect.ValueOf(bean)
- if beanValue.Kind() != reflect.Ptr {
- return false, errors.New("needs a pointer to a value")
- } else if beanValue.Elem().Kind() == reflect.Ptr {
- return false, errors.New("a pointer to a pointer is not allowed")
- }
-
- if beanValue.Elem().Kind() == reflect.Struct {
- if err := session.statement.setRefBean(bean); err != nil {
- return false, err
- }
- }
-
- var sqlStr string
- var args []interface{}
- var err error
-
- if session.statement.RawSQL == "" {
- if len(session.statement.TableName()) <= 0 {
- return false, ErrTableNotFound
- }
- session.statement.Limit(1)
- sqlStr, args, err = session.statement.genGetSQL(bean)
- if err != nil {
- return false, err
- }
- } else {
- sqlStr = session.statement.RawSQL
- args = session.statement.RawParams
- }
-
- table := session.statement.RefTable
-
- if session.canCache() && beanValue.Elem().Kind() == reflect.Struct {
- if cacher := session.engine.getCacher(session.statement.TableName()); cacher != nil &&
- !session.statement.unscoped {
- has, err := session.cacheGet(bean, sqlStr, args...)
- if err != ErrCacheFailed {
- return has, err
- }
- }
- }
-
- context := session.statement.context
- if context != nil {
- res := context.Get(fmt.Sprintf("%v-%v", sqlStr, args))
- if res != nil {
- structValue := reflect.Indirect(reflect.ValueOf(bean))
- structValue.Set(reflect.Indirect(reflect.ValueOf(res)))
- session.lastSQL = ""
- session.lastSQLArgs = nil
- return true, nil
- }
- }
-
- has, err := session.nocacheGet(beanValue.Elem().Kind(), table, bean, sqlStr, args...)
- if err != nil || !has {
- return has, err
- }
-
- if context != nil {
- context.Put(fmt.Sprintf("%v-%v", sqlStr, args), bean)
- }
-
- return true, nil
-}
-
-func (session *Session) nocacheGet(beanKind reflect.Kind, table *core.Table, bean interface{}, sqlStr string, args ...interface{}) (bool, error) {
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- if !rows.Next() {
- if rows.Err() != nil {
- return false, rows.Err()
- }
- return false, nil
- }
-
- switch bean.(type) {
- case sql.NullInt64, sql.NullBool, sql.NullFloat64, sql.NullString:
- return true, rows.Scan(&bean)
- case *sql.NullInt64, *sql.NullBool, *sql.NullFloat64, *sql.NullString:
- return true, rows.Scan(bean)
- }
-
- switch beanKind {
- case reflect.Struct:
- fields, err := rows.Columns()
- if err != nil {
- // WARN: Alougth rows return true, but get fields failed
- return true, err
- }
-
- scanResults, err := session.row2Slice(rows, fields, bean)
- if err != nil {
- return false, err
- }
- // close it before covert data
- rows.Close()
-
- dataStruct := rValue(bean)
- _, err = session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
- if err != nil {
- return true, err
- }
-
- return true, session.executeProcessors()
- case reflect.Slice:
- err = rows.ScanSlice(bean)
- case reflect.Map:
- err = rows.ScanMap(bean)
- default:
- err = rows.Scan(bean)
- }
-
- return true, err
-}
-
-func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interface{}) (has bool, err error) {
- // if has no reftable, then don't use cache currently
- if !session.canCache() {
- return false, ErrCacheFailed
- }
-
- for _, filter := range session.engine.dialect.Filters() {
- sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
- }
- newsql := session.statement.convertIDSQL(sqlStr)
- if newsql == "" {
- return false, ErrCacheFailed
- }
-
- tableName := session.statement.TableName()
- cacher := session.engine.getCacher(tableName)
-
- session.engine.logger.Debug("[cacheGet] find sql:", newsql, args)
- table := session.statement.RefTable
- ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
- if err != nil {
- var res = make([]string, len(table.PrimaryKeys))
- rows, err := session.NoCache().queryRows(newsql, args...)
- if err != nil {
- return false, err
- }
- defer rows.Close()
-
- if rows.Next() {
- err = rows.ScanSlice(&res)
- if err != nil {
- return false, err
- }
- } else {
- return false, ErrCacheFailed
- }
-
- var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
- for i, col := range table.PKColumns() {
- if col.SQLType.IsText() {
- pk[i] = res[i]
- } else if col.SQLType.IsNumeric() {
- n, err := strconv.ParseInt(res[i], 10, 64)
- if err != nil {
- return false, err
- }
- pk[i] = n
- } else {
- return false, errors.New("unsupported")
- }
- }
-
- ids = []core.PK{pk}
- session.engine.logger.Debug("[cacheGet] cache ids:", newsql, ids)
- err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
- if err != nil {
- return false, err
- }
- } else {
- session.engine.logger.Debug("[cacheGet] cache hit sql:", newsql, ids)
- }
-
- if len(ids) > 0 {
- structValue := reflect.Indirect(reflect.ValueOf(bean))
- id := ids[0]
- session.engine.logger.Debug("[cacheGet] get bean:", tableName, id)
- sid, err := id.ToString()
- if err != nil {
- return false, err
- }
- cacheBean := cacher.GetBean(tableName, sid)
- if cacheBean == nil {
- cacheBean = bean
- has, err = session.nocacheGet(reflect.Struct, table, cacheBean, sqlStr, args...)
- if err != nil || !has {
- return has, err
- }
-
- session.engine.logger.Debug("[cacheGet] cache bean:", tableName, id, cacheBean)
- cacher.PutBean(tableName, sid, cacheBean)
- } else {
- session.engine.logger.Debug("[cacheGet] cache hit bean:", tableName, id, cacheBean)
- has = true
- }
- structValue.Set(reflect.Indirect(reflect.ValueOf(cacheBean)))
-
- return has, nil
- }
- return false, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_insert.go b/vendor/github.com/go-xorm/xorm/session_insert.go
deleted file mode 100644
index 3cff48f..0000000
--- a/vendor/github.com/go-xorm/xorm/session_insert.go
+++ /dev/null
@@ -1,747 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "strings"
-
- "xorm.io/core"
-)
-
-// Insert insert one or more beans
-func (session *Session) Insert(beans ...interface{}) (int64, error) {
- var affected int64
- var err error
-
- if session.isAutoClose {
- defer session.Close()
- }
-
- for _, bean := range beans {
- switch bean.(type) {
- case map[string]interface{}:
- cnt, err := session.insertMapInterface(bean.(map[string]interface{}))
- if err != nil {
- return affected, err
- }
- affected += cnt
- case []map[string]interface{}:
- s := bean.([]map[string]interface{})
- session.autoResetStatement = false
- for i := 0; i < len(s); i++ {
- cnt, err := session.insertMapInterface(s[i])
- if err != nil {
- return affected, err
- }
- affected += cnt
- }
- case map[string]string:
- cnt, err := session.insertMapString(bean.(map[string]string))
- if err != nil {
- return affected, err
- }
- affected += cnt
- case []map[string]string:
- s := bean.([]map[string]string)
- session.autoResetStatement = false
- for i := 0; i < len(s); i++ {
- cnt, err := session.insertMapString(s[i])
- if err != nil {
- return affected, err
- }
- affected += cnt
- }
- default:
- sliceValue := reflect.Indirect(reflect.ValueOf(bean))
- if sliceValue.Kind() == reflect.Slice {
- size := sliceValue.Len()
- if size > 0 {
- if session.engine.SupportInsertMany() {
- cnt, err := session.innerInsertMulti(bean)
- if err != nil {
- return affected, err
- }
- affected += cnt
- } else {
- for i := 0; i < size; i++ {
- cnt, err := session.innerInsert(sliceValue.Index(i).Interface())
- if err != nil {
- return affected, err
- }
- affected += cnt
- }
- }
- }
- } else {
- cnt, err := session.innerInsert(bean)
- if err != nil {
- return affected, err
- }
- affected += cnt
- }
- }
- }
-
- return affected, err
-}
-
-func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error) {
- sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
- if sliceValue.Kind() != reflect.Slice {
- return 0, errors.New("needs a pointer to a slice")
- }
-
- if sliceValue.Len() <= 0 {
- return 0, errors.New("could not insert a empty slice")
- }
-
- if err := session.statement.setRefBean(sliceValue.Index(0).Interface()); err != nil {
- return 0, err
- }
-
- tableName := session.statement.TableName()
- if len(tableName) <= 0 {
- return 0, ErrTableNotFound
- }
-
- table := session.statement.RefTable
- size := sliceValue.Len()
-
- var colNames []string
- var colMultiPlaces []string
- var args []interface{}
- var cols []*core.Column
-
- for i := 0; i < size; i++ {
- v := sliceValue.Index(i)
- vv := reflect.Indirect(v)
- elemValue := v.Interface()
- var colPlaces []string
-
- // handle BeforeInsertProcessor
- // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
- for _, closure := range session.beforeClosures {
- closure(elemValue)
- }
-
- if processor, ok := interface{}(elemValue).(BeforeInsertProcessor); ok {
- processor.BeforeInsert()
- }
- // --
-
- if i == 0 {
- for _, col := range table.Columns() {
- ptrFieldValue, err := col.ValueOfV(&vv)
- if err != nil {
- return 0, err
- }
- fieldValue := *ptrFieldValue
- if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
- continue
- }
- if col.MapType == core.ONLYFROMDB {
- continue
- }
- if col.IsDeleted {
- continue
- }
- if session.statement.omitColumnMap.contain(col.Name) {
- continue
- }
- if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) {
- continue
- }
- if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime {
- val, t := session.engine.nowTime(col)
- args = append(args, val)
-
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- } else if col.IsVersion && session.statement.checkVersion {
- args = append(args, 1)
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnInt(bean, col, 1)
- })
- } else {
- arg, err := session.value2Interface(col, fieldValue)
- if err != nil {
- return 0, err
- }
- args = append(args, arg)
- }
-
- colNames = append(colNames, col.Name)
- cols = append(cols, col)
- colPlaces = append(colPlaces, "?")
- }
- } else {
- for _, col := range cols {
- ptrFieldValue, err := col.ValueOfV(&vv)
- if err != nil {
- return 0, err
- }
- fieldValue := *ptrFieldValue
-
- if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
- continue
- }
- if col.MapType == core.ONLYFROMDB {
- continue
- }
- if col.IsDeleted {
- continue
- }
- if session.statement.omitColumnMap.contain(col.Name) {
- continue
- }
- if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) {
- continue
- }
- if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime {
- val, t := session.engine.nowTime(col)
- args = append(args, val)
-
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- } else if col.IsVersion && session.statement.checkVersion {
- args = append(args, 1)
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnInt(bean, col, 1)
- })
- } else {
- arg, err := session.value2Interface(col, fieldValue)
- if err != nil {
- return 0, err
- }
- args = append(args, arg)
- }
-
- colPlaces = append(colPlaces, "?")
- }
- }
- colMultiPlaces = append(colMultiPlaces, strings.Join(colPlaces, ", "))
- }
- cleanupProcessorsClosures(&session.beforeClosures)
-
- var sql string
- if session.engine.dialect.DBType() == core.ORACLE {
- temp := fmt.Sprintf(") INTO %s (%v%v%v) VALUES (",
- session.engine.Quote(tableName),
- session.engine.QuoteStr(),
- strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
- session.engine.QuoteStr())
- sql = fmt.Sprintf("INSERT ALL INTO %s (%v%v%v) VALUES (%v) SELECT 1 FROM DUAL",
- session.engine.Quote(tableName),
- session.engine.QuoteStr(),
- strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
- session.engine.QuoteStr(),
- strings.Join(colMultiPlaces, temp))
- } else {
- sql = fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
- session.engine.Quote(tableName),
- session.engine.QuoteStr(),
- strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
- session.engine.QuoteStr(),
- strings.Join(colMultiPlaces, "),("))
- }
- res, err := session.exec(sql, args...)
- if err != nil {
- return 0, err
- }
-
- session.cacheInsert(tableName)
-
- lenAfterClosures := len(session.afterClosures)
- for i := 0; i < size; i++ {
- elemValue := reflect.Indirect(sliceValue.Index(i)).Addr().Interface()
-
- // handle AfterInsertProcessor
- if session.isAutoCommit {
- // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
- for _, closure := range session.afterClosures {
- closure(elemValue)
- }
- if processor, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
- processor.AfterInsert()
- }
- } else {
- if lenAfterClosures > 0 {
- if value, has := session.afterInsertBeans[elemValue]; has && value != nil {
- *value = append(*value, session.afterClosures...)
- } else {
- afterClosures := make([]func(interface{}), lenAfterClosures)
- copy(afterClosures, session.afterClosures)
- session.afterInsertBeans[elemValue] = &afterClosures
- }
- } else {
- if _, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
- session.afterInsertBeans[elemValue] = nil
- }
- }
- }
- }
-
- cleanupProcessorsClosures(&session.afterClosures)
- return res.RowsAffected()
-}
-
-// InsertMulti insert multiple records
-func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
- if sliceValue.Kind() != reflect.Slice {
- return 0, ErrParamsType
-
- }
-
- if sliceValue.Len() <= 0 {
- return 0, nil
- }
-
- return session.innerInsertMulti(rowsSlicePtr)
-}
-
-func (session *Session) innerInsert(bean interface{}) (int64, error) {
- if err := session.statement.setRefBean(bean); err != nil {
- return 0, err
- }
- if len(session.statement.TableName()) <= 0 {
- return 0, ErrTableNotFound
- }
-
- table := session.statement.RefTable
-
- // handle BeforeInsertProcessor
- for _, closure := range session.beforeClosures {
- closure(bean)
- }
- cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
-
- if processor, ok := interface{}(bean).(BeforeInsertProcessor); ok {
- processor.BeforeInsert()
- }
-
- colNames, args, err := session.genInsertColumns(bean)
- if err != nil {
- return 0, err
- }
- // insert expr columns, override if exists
- exprColumns := session.statement.getExpr()
- exprColVals := make([]string, 0, len(exprColumns))
- for _, v := range exprColumns {
- // remove the expr columns
- for i, colName := range colNames {
- if colName == v.colName {
- colNames = append(colNames[:i], colNames[i+1:]...)
- args = append(args[:i], args[i+1:]...)
- }
- }
-
- // append expr column to the end
- colNames = append(colNames, v.colName)
- exprColVals = append(exprColVals, v.expr)
- }
-
- colPlaces := strings.Repeat("?, ", len(colNames)-len(exprColumns))
- if len(exprColVals) > 0 {
- colPlaces = colPlaces + strings.Join(exprColVals, ", ")
- } else {
- if len(colPlaces) > 0 {
- colPlaces = colPlaces[0 : len(colPlaces)-2]
- }
- }
-
- var sqlStr string
- var tableName = session.statement.TableName()
- var output string
- if session.engine.dialect.DBType() == core.MSSQL && len(table.AutoIncrement) > 0 {
- output = fmt.Sprintf(" OUTPUT Inserted.%s", table.AutoIncrement)
- }
- if len(colPlaces) > 0 {
- sqlStr = fmt.Sprintf("INSERT INTO %s (%v%v%v)%s VALUES (%v)",
- session.engine.Quote(tableName),
- session.engine.QuoteStr(),
- strings.Join(colNames, session.engine.Quote(", ")),
- session.engine.QuoteStr(),
- output,
- colPlaces)
- } else {
- if session.engine.dialect.DBType() == core.MYSQL {
- sqlStr = fmt.Sprintf("INSERT INTO %s VALUES ()", session.engine.Quote(tableName))
- } else {
- sqlStr = fmt.Sprintf("INSERT INTO %s%s DEFAULT VALUES", session.engine.Quote(tableName), output)
- }
- }
-
- if len(table.AutoIncrement) > 0 && session.engine.dialect.DBType() == core.POSTGRES {
- sqlStr = sqlStr + " RETURNING " + session.engine.Quote(table.AutoIncrement)
- }
-
- handleAfterInsertProcessorFunc := func(bean interface{}) {
- if session.isAutoCommit {
- for _, closure := range session.afterClosures {
- closure(bean)
- }
- if processor, ok := interface{}(bean).(AfterInsertProcessor); ok {
- processor.AfterInsert()
- }
- } else {
- lenAfterClosures := len(session.afterClosures)
- if lenAfterClosures > 0 {
- if value, has := session.afterInsertBeans[bean]; has && value != nil {
- *value = append(*value, session.afterClosures...)
- } else {
- afterClosures := make([]func(interface{}), lenAfterClosures)
- copy(afterClosures, session.afterClosures)
- session.afterInsertBeans[bean] = &afterClosures
- }
-
- } else {
- if _, ok := interface{}(bean).(AfterInsertProcessor); ok {
- session.afterInsertBeans[bean] = nil
- }
- }
- }
- cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
- }
-
- // for postgres, many of them didn't implement lastInsertId, so we should
- // implemented it ourself.
- if session.engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 {
- res, err := session.queryBytes("select seq_atable.currval from dual", args...)
- if err != nil {
- return 0, err
- }
-
- defer handleAfterInsertProcessorFunc(bean)
-
- session.cacheInsert(tableName)
-
- if table.Version != "" && session.statement.checkVersion {
- verValue, err := table.VersionColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- } else if verValue.IsValid() && verValue.CanSet() {
- session.incrVersionFieldValue(verValue)
- }
- }
-
- if len(res) < 1 {
- return 0, errors.New("insert no error but not returned id")
- }
-
- idByte := res[0][table.AutoIncrement]
- id, err := strconv.ParseInt(string(idByte), 10, 64)
- if err != nil || id <= 0 {
- return 1, err
- }
-
- aiValue, err := table.AutoIncrColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- }
-
- if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
- return 1, nil
- }
-
- aiValue.Set(int64ToIntValue(id, aiValue.Type()))
-
- return 1, nil
- } else if len(table.AutoIncrement) > 0 && (session.engine.dialect.DBType() == core.POSTGRES || session.engine.dialect.DBType() == core.MSSQL) {
- res, err := session.queryBytes(sqlStr, args...)
-
- if err != nil {
- return 0, err
- }
- defer handleAfterInsertProcessorFunc(bean)
-
- session.cacheInsert(tableName)
-
- if table.Version != "" && session.statement.checkVersion {
- verValue, err := table.VersionColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- } else if verValue.IsValid() && verValue.CanSet() {
- session.incrVersionFieldValue(verValue)
- }
- }
-
- if len(res) < 1 {
- return 0, errors.New("insert successfully but not returned id")
- }
-
- idByte := res[0][table.AutoIncrement]
- id, err := strconv.ParseInt(string(idByte), 10, 64)
- if err != nil || id <= 0 {
- return 1, err
- }
-
- aiValue, err := table.AutoIncrColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- }
-
- if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
- return 1, nil
- }
-
- aiValue.Set(int64ToIntValue(id, aiValue.Type()))
-
- return 1, nil
- } else {
- res, err := session.exec(sqlStr, args...)
- if err != nil {
- return 0, err
- }
-
- defer handleAfterInsertProcessorFunc(bean)
-
- session.cacheInsert(tableName)
-
- if table.Version != "" && session.statement.checkVersion {
- verValue, err := table.VersionColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- } else if verValue.IsValid() && verValue.CanSet() {
- session.incrVersionFieldValue(verValue)
- }
- }
-
- if table.AutoIncrement == "" {
- return res.RowsAffected()
- }
-
- var id int64
- id, err = res.LastInsertId()
- if err != nil || id <= 0 {
- return res.RowsAffected()
- }
-
- aiValue, err := table.AutoIncrColumn().ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- }
-
- if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
- return res.RowsAffected()
- }
-
- aiValue.Set(int64ToIntValue(id, aiValue.Type()))
-
- return res.RowsAffected()
- }
-}
-
-// InsertOne insert only one struct into database as a record.
-// The in parameter bean must a struct or a point to struct. The return
-// parameter is inserted and error
-func (session *Session) InsertOne(bean interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- return session.innerInsert(bean)
-}
-
-func (session *Session) cacheInsert(table string) error {
- if !session.statement.UseCache {
- return nil
- }
- cacher := session.engine.getCacher(table)
- if cacher == nil {
- return nil
- }
- session.engine.logger.Debug("[cache] clear sql:", table)
- cacher.ClearIds(table)
- return nil
-}
-
-// genInsertColumns generates insert needed columns
-func (session *Session) genInsertColumns(bean interface{}) ([]string, []interface{}, error) {
- table := session.statement.RefTable
- colNames := make([]string, 0, len(table.ColumnsSeq()))
- args := make([]interface{}, 0, len(table.ColumnsSeq()))
-
- for _, col := range table.Columns() {
- if col.MapType == core.ONLYFROMDB {
- continue
- }
-
- if col.IsDeleted {
- continue
- }
-
- if session.statement.omitColumnMap.contain(col.Name) {
- continue
- }
-
- if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) {
- continue
- }
-
- if _, ok := session.statement.incrColumns[col.Name]; ok {
- continue
- } else if _, ok := session.statement.decrColumns[col.Name]; ok {
- continue
- }
-
- fieldValuePtr, err := col.ValueOf(bean)
- if err != nil {
- return nil, nil, err
- }
- fieldValue := *fieldValuePtr
-
- if col.IsAutoIncrement {
- switch fieldValue.Type().Kind() {
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
- if fieldValue.Int() == 0 {
- continue
- }
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
- if fieldValue.Uint() == 0 {
- continue
- }
- case reflect.String:
- if len(fieldValue.String()) == 0 {
- continue
- }
- case reflect.Ptr:
- if fieldValue.Pointer() == 0 {
- continue
- }
- }
- }
-
- // !evalphobia! set fieldValue as nil when column is nullable and zero-value
- if _, ok := getFlagForColumn(session.statement.nullableMap, col); ok {
- if col.Nullable && isZero(fieldValue.Interface()) {
- var nilValue *int
- fieldValue = reflect.ValueOf(nilValue)
- }
- }
-
- if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
- // if time is non-empty, then set to auto time
- val, t := session.engine.nowTime(col)
- args = append(args, val)
-
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- } else if col.IsVersion && session.statement.checkVersion {
- args = append(args, 1)
- } else {
- arg, err := session.value2Interface(col, fieldValue)
- if err != nil {
- return colNames, args, err
- }
- args = append(args, arg)
- }
-
- colNames = append(colNames, col.Name)
- }
- return colNames, args, nil
-}
-
-func (session *Session) insertMapInterface(m map[string]interface{}) (int64, error) {
- if len(m) == 0 {
- return 0, ErrParamsType
- }
-
- var columns = make([]string, 0, len(m))
- for k := range m {
- columns = append(columns, k)
- }
- sort.Strings(columns)
-
- qm := strings.Repeat("?,", len(columns))
- qm = "(" + qm[:len(qm)-1] + ")"
-
- tableName := session.statement.TableName()
- if len(tableName) <= 0 {
- return 0, ErrTableNotFound
- }
-
- var sql = fmt.Sprintf("INSERT INTO %s (`%s`) VALUES %s", session.engine.Quote(tableName), strings.Join(columns, "`,`"), qm)
- var args = make([]interface{}, 0, len(m))
- for _, colName := range columns {
- args = append(args, m[colName])
- }
-
- if err := session.cacheInsert(tableName); err != nil {
- return 0, err
- }
-
- res, err := session.exec(sql, args...)
- if err != nil {
- return 0, err
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return 0, err
- }
- return affected, nil
-}
-
-func (session *Session) insertMapString(m map[string]string) (int64, error) {
- if len(m) == 0 {
- return 0, ErrParamsType
- }
-
- var columns = make([]string, 0, len(m))
- for k := range m {
- columns = append(columns, k)
- }
- sort.Strings(columns)
-
- qm := strings.Repeat("?,", len(columns))
- qm = "(" + qm[:len(qm)-1] + ")"
-
- tableName := session.statement.TableName()
- if len(tableName) <= 0 {
- return 0, ErrTableNotFound
- }
-
- var sql = fmt.Sprintf("INSERT INTO %s (`%s`) VALUES %s", session.engine.Quote(tableName), strings.Join(columns, "`,`"), qm)
- var args = make([]interface{}, 0, len(m))
- for _, colName := range columns {
- args = append(args, m[colName])
- }
-
- if err := session.cacheInsert(tableName); err != nil {
- return 0, err
- }
-
- res, err := session.exec(sql, args...)
- if err != nil {
- return 0, err
- }
- affected, err := res.RowsAffected()
- if err != nil {
- return 0, err
- }
- return affected, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_iterate.go b/vendor/github.com/go-xorm/xorm/session_iterate.go
deleted file mode 100644
index ca996c2..0000000
--- a/vendor/github.com/go-xorm/xorm/session_iterate.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import "reflect"
-
-// IterFunc only use by Iterate
-type IterFunc func(idx int, bean interface{}) error
-
-// Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
-// are conditions.
-func (session *Session) Rows(bean interface{}) (*Rows, error) {
- return newRows(session, bean)
-}
-
-// Iterate record by record handle records from table, condiBeans's non-empty fields
-// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
-// map[int64]*Struct
-func (session *Session) Iterate(bean interface{}, fun IterFunc) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- if session.statement.lastError != nil {
- return session.statement.lastError
- }
-
- if session.statement.bufferSize > 0 {
- return session.bufferIterate(bean, fun)
- }
-
- rows, err := session.Rows(bean)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- i := 0
- for rows.Next() {
- b := reflect.New(rows.beanType).Interface()
- err = rows.Scan(b)
- if err != nil {
- return err
- }
- err = fun(i, b)
- if err != nil {
- return err
- }
- i++
- }
- return err
-}
-
-// BufferSize sets the buffersize for iterate
-func (session *Session) BufferSize(size int) *Session {
- session.statement.bufferSize = size
- return session
-}
-
-func (session *Session) bufferIterate(bean interface{}, fun IterFunc) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- var bufferSize = session.statement.bufferSize
- var limit = session.statement.LimitN
- if limit > 0 && bufferSize > limit {
- bufferSize = limit
- }
- var start = session.statement.Start
- v := rValue(bean)
- sliceType := reflect.SliceOf(v.Type())
- var idx = 0
- for {
- slice := reflect.New(sliceType)
- if err := session.Limit(bufferSize, start).find(slice.Interface(), bean); err != nil {
- return err
- }
-
- for i := 0; i < slice.Elem().Len(); i++ {
- if err := fun(idx, slice.Elem().Index(i).Addr().Interface()); err != nil {
- return err
- }
- idx++
- }
-
- start = start + slice.Elem().Len()
- if limit > 0 && idx+bufferSize > limit {
- bufferSize = limit - idx
- }
-
- if bufferSize <= 0 || slice.Elem().Len() < bufferSize || idx == limit {
- break
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_query.go b/vendor/github.com/go-xorm/xorm/session_query.go
deleted file mode 100644
index 21c00b8..0000000
--- a/vendor/github.com/go-xorm/xorm/session_query.go
+++ /dev/null
@@ -1,320 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "time"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-func (session *Session) genQuerySQL(sqlOrArgs ...interface{}) (string, []interface{}, error) {
- if len(sqlOrArgs) > 0 {
- return convertSQLOrArgs(sqlOrArgs...)
- }
-
- if session.statement.RawSQL != "" {
- return session.statement.RawSQL, session.statement.RawParams, nil
- }
-
- if len(session.statement.TableName()) <= 0 {
- return "", nil, ErrTableNotFound
- }
-
- var columnStr = session.statement.ColumnStr
- if len(session.statement.selectStr) > 0 {
- columnStr = session.statement.selectStr
- } else {
- if session.statement.JoinStr == "" {
- if columnStr == "" {
- if session.statement.GroupByStr != "" {
- columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
- } else {
- columnStr = session.statement.genColumnStr()
- }
- }
- } else {
- if columnStr == "" {
- if session.statement.GroupByStr != "" {
- columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
- } else {
- columnStr = "*"
- }
- }
- }
- if columnStr == "" {
- columnStr = "*"
- }
- }
-
- if err := session.statement.processIDParam(); err != nil {
- return "", nil, err
- }
-
- condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
- if err != nil {
- return "", nil, err
- }
-
- args := append(session.statement.joinArgs, condArgs...)
- sqlStr, err := session.statement.genSelectSQL(columnStr, condSQL, true, true)
- if err != nil {
- return "", nil, err
- }
- // for mssql and use limit
- qs := strings.Count(sqlStr, "?")
- if len(args)*2 == qs {
- args = append(args, args...)
- }
-
- return sqlStr, args, nil
-}
-
-// Query runs a raw sql and return records as []map[string][]byte
-func (session *Session) Query(sqlOrArgs ...interface{}) ([]map[string][]byte, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- sqlStr, args, err := session.genQuerySQL(sqlOrArgs...)
- if err != nil {
- return nil, err
- }
-
- return session.queryBytes(sqlStr, args...)
-}
-
-func value2String(rawValue *reflect.Value) (str string, err error) {
- aa := reflect.TypeOf((*rawValue).Interface())
- vv := reflect.ValueOf((*rawValue).Interface())
- switch aa.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- str = strconv.FormatInt(vv.Int(), 10)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- str = strconv.FormatUint(vv.Uint(), 10)
- case reflect.Float32, reflect.Float64:
- str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
- case reflect.String:
- str = vv.String()
- case reflect.Array, reflect.Slice:
- switch aa.Elem().Kind() {
- case reflect.Uint8:
- data := rawValue.Interface().([]byte)
- str = string(data)
- if str == "\x00" {
- str = "0"
- }
- default:
- err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
- }
- // time type
- case reflect.Struct:
- if aa.ConvertibleTo(core.TimeType) {
- str = vv.Convert(core.TimeType).Interface().(time.Time).Format(time.RFC3339Nano)
- } else {
- err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
- }
- case reflect.Bool:
- str = strconv.FormatBool(vv.Bool())
- case reflect.Complex128, reflect.Complex64:
- str = fmt.Sprintf("%v", vv.Complex())
- /* TODO: unsupported types below
- case reflect.Map:
- case reflect.Ptr:
- case reflect.Uintptr:
- case reflect.UnsafePointer:
- case reflect.Chan, reflect.Func, reflect.Interface:
- */
- default:
- err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
- }
- return
-}
-
-func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string, err error) {
- result := make(map[string]string)
- scanResultContainers := make([]interface{}, len(fields))
- for i := 0; i < len(fields); i++ {
- var scanResultContainer interface{}
- scanResultContainers[i] = &scanResultContainer
- }
- if err := rows.Scan(scanResultContainers...); err != nil {
- return nil, err
- }
-
- for ii, key := range fields {
- rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
- // if row is null then as empty string
- if rawValue.Interface() == nil {
- result[key] = ""
- continue
- }
-
- if data, err := value2String(&rawValue); err == nil {
- result[key] = data
- } else {
- return nil, err
- }
- }
- return result, nil
-}
-
-func row2sliceStr(rows *core.Rows, fields []string) (results []string, err error) {
- result := make([]string, 0, len(fields))
- scanResultContainers := make([]interface{}, len(fields))
- for i := 0; i < len(fields); i++ {
- var scanResultContainer interface{}
- scanResultContainers[i] = &scanResultContainer
- }
- if err := rows.Scan(scanResultContainers...); err != nil {
- return nil, err
- }
-
- for i := 0; i < len(fields); i++ {
- rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[i]))
- // if row is null then as empty string
- if rawValue.Interface() == nil {
- result = append(result, "")
- continue
- }
-
- if data, err := value2String(&rawValue); err == nil {
- result = append(result, data)
- } else {
- return nil, err
- }
- }
- return result, nil
-}
-
-func rows2Strings(rows *core.Rows) (resultsSlice []map[string]string, err error) {
- fields, err := rows.Columns()
- if err != nil {
- return nil, err
- }
- for rows.Next() {
- result, err := row2mapStr(rows, fields)
- if err != nil {
- return nil, err
- }
- resultsSlice = append(resultsSlice, result)
- }
-
- return resultsSlice, nil
-}
-
-func rows2SliceString(rows *core.Rows) (resultsSlice [][]string, err error) {
- fields, err := rows.Columns()
- if err != nil {
- return nil, err
- }
- for rows.Next() {
- record, err := row2sliceStr(rows, fields)
- if err != nil {
- return nil, err
- }
- resultsSlice = append(resultsSlice, record)
- }
-
- return resultsSlice, nil
-}
-
-// QueryString runs a raw sql and return records as []map[string]string
-func (session *Session) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- sqlStr, args, err := session.genQuerySQL(sqlOrArgs...)
- if err != nil {
- return nil, err
- }
-
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- return rows2Strings(rows)
-}
-
-// QuerySliceString runs a raw sql and return records as [][]string
-func (session *Session) QuerySliceString(sqlOrArgs ...interface{}) ([][]string, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- sqlStr, args, err := session.genQuerySQL(sqlOrArgs...)
- if err != nil {
- return nil, err
- }
-
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- return rows2SliceString(rows)
-}
-
-func row2mapInterface(rows *core.Rows, fields []string) (resultsMap map[string]interface{}, err error) {
- resultsMap = make(map[string]interface{}, len(fields))
- scanResultContainers := make([]interface{}, len(fields))
- for i := 0; i < len(fields); i++ {
- var scanResultContainer interface{}
- scanResultContainers[i] = &scanResultContainer
- }
- if err := rows.Scan(scanResultContainers...); err != nil {
- return nil, err
- }
-
- for ii, key := range fields {
- resultsMap[key] = reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])).Interface()
- }
- return
-}
-
-func rows2Interfaces(rows *core.Rows) (resultsSlice []map[string]interface{}, err error) {
- fields, err := rows.Columns()
- if err != nil {
- return nil, err
- }
- for rows.Next() {
- result, err := row2mapInterface(rows, fields)
- if err != nil {
- return nil, err
- }
- resultsSlice = append(resultsSlice, result)
- }
-
- return resultsSlice, nil
-}
-
-// QueryInterface runs a raw sql and return records as []map[string]interface{}
-func (session *Session) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- sqlStr, args, err := session.genQuerySQL(sqlOrArgs...)
- if err != nil {
- return nil, err
- }
-
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- return rows2Interfaces(rows)
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_raw.go b/vendor/github.com/go-xorm/xorm/session_raw.go
deleted file mode 100644
index 67648ef..0000000
--- a/vendor/github.com/go-xorm/xorm/session_raw.go
+++ /dev/null
@@ -1,227 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "reflect"
- "time"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-func (session *Session) queryPreprocess(sqlStr *string, paramStr ...interface{}) {
- for _, filter := range session.engine.dialect.Filters() {
- *sqlStr = filter.Do(*sqlStr, session.engine.dialect, session.statement.RefTable)
- }
-
- session.lastSQL = *sqlStr
- session.lastSQLArgs = paramStr
-}
-
-func (session *Session) queryRows(sqlStr string, args ...interface{}) (*core.Rows, error) {
- defer session.resetStatement()
-
- session.queryPreprocess(&sqlStr, args...)
-
- if session.engine.showSQL {
- if session.engine.showExecTime {
- b4ExecTime := time.Now()
- defer func() {
- execDuration := time.Since(b4ExecTime)
- if len(args) > 0 {
- session.engine.logger.Infof("[SQL] %s %#v - took: %v", sqlStr, args, execDuration)
- } else {
- session.engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
- }
- }()
- } else {
- if len(args) > 0 {
- session.engine.logger.Infof("[SQL] %v %#v", sqlStr, args)
- } else {
- session.engine.logger.Infof("[SQL] %v", sqlStr)
- }
- }
- }
-
- if session.isAutoCommit {
- var db *core.DB
- if session.sessionType == groupSession {
- db = session.engine.engineGroup.Slave().DB()
- } else {
- db = session.DB()
- }
-
- if session.prepareStmt {
- // don't clear stmt since session will cache them
- stmt, err := session.doPrepare(db, sqlStr)
- if err != nil {
- return nil, err
- }
-
- rows, err := stmt.QueryContext(session.ctx, args...)
- if err != nil {
- return nil, err
- }
- return rows, nil
- }
-
- rows, err := db.QueryContext(session.ctx, sqlStr, args...)
- if err != nil {
- return nil, err
- }
- return rows, nil
- }
-
- rows, err := session.tx.QueryContext(session.ctx, sqlStr, args...)
- if err != nil {
- return nil, err
- }
- return rows, nil
-}
-
-func (session *Session) queryRow(sqlStr string, args ...interface{}) *core.Row {
- return core.NewRow(session.queryRows(sqlStr, args...))
-}
-
-func value2Bytes(rawValue *reflect.Value) ([]byte, error) {
- str, err := value2String(rawValue)
- if err != nil {
- return nil, err
- }
- return []byte(str), nil
-}
-
-func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, err error) {
- result := make(map[string][]byte)
- scanResultContainers := make([]interface{}, len(fields))
- for i := 0; i < len(fields); i++ {
- var scanResultContainer interface{}
- scanResultContainers[i] = &scanResultContainer
- }
- if err := rows.Scan(scanResultContainers...); err != nil {
- return nil, err
- }
-
- for ii, key := range fields {
- rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
- //if row is null then ignore
- if rawValue.Interface() == nil {
- result[key] = []byte{}
- continue
- }
-
- if data, err := value2Bytes(&rawValue); err == nil {
- result[key] = data
- } else {
- return nil, err // !nashtsai! REVIEW, should return err or just error log?
- }
- }
- return result, nil
-}
-
-func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) {
- fields, err := rows.Columns()
- if err != nil {
- return nil, err
- }
- for rows.Next() {
- result, err := row2map(rows, fields)
- if err != nil {
- return nil, err
- }
- resultsSlice = append(resultsSlice, result)
- }
-
- return resultsSlice, nil
-}
-
-func (session *Session) queryBytes(sqlStr string, args ...interface{}) ([]map[string][]byte, error) {
- rows, err := session.queryRows(sqlStr, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- return rows2maps(rows)
-}
-
-func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, error) {
- defer session.resetStatement()
-
- session.queryPreprocess(&sqlStr, args...)
-
- if session.engine.showSQL {
- if session.engine.showExecTime {
- b4ExecTime := time.Now()
- defer func() {
- execDuration := time.Since(b4ExecTime)
- if len(args) > 0 {
- session.engine.logger.Infof("[SQL] %s %#v - took: %v", sqlStr, args, execDuration)
- } else {
- session.engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
- }
- }()
- } else {
- if len(args) > 0 {
- session.engine.logger.Infof("[SQL] %v %#v", sqlStr, args)
- } else {
- session.engine.logger.Infof("[SQL] %v", sqlStr)
- }
- }
- }
-
- if !session.isAutoCommit {
- return session.tx.ExecContext(session.ctx, sqlStr, args...)
- }
-
- if session.prepareStmt {
- stmt, err := session.doPrepare(session.DB(), sqlStr)
- if err != nil {
- return nil, err
- }
-
- res, err := stmt.ExecContext(session.ctx, args...)
- if err != nil {
- return nil, err
- }
- return res, nil
- }
-
- return session.DB().ExecContext(session.ctx, sqlStr, args...)
-}
-
-func convertSQLOrArgs(sqlOrArgs ...interface{}) (string, []interface{}, error) {
- switch sqlOrArgs[0].(type) {
- case string:
- return sqlOrArgs[0].(string), sqlOrArgs[1:], nil
- case *builder.Builder:
- return sqlOrArgs[0].(*builder.Builder).ToSQL()
- case builder.Builder:
- bd := sqlOrArgs[0].(builder.Builder)
- return bd.ToSQL()
- }
-
- return "", nil, ErrUnSupportedType
-}
-
-// Exec raw sql
-func (session *Session) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- if len(sqlOrArgs) == 0 {
- return nil, ErrUnSupportedType
- }
-
- sqlStr, args, err := convertSQLOrArgs(sqlOrArgs...)
- if err != nil {
- return nil, err
- }
-
- return session.exec(sqlStr, args...)
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_schema.go b/vendor/github.com/go-xorm/xorm/session_schema.go
deleted file mode 100644
index da5c885..0000000
--- a/vendor/github.com/go-xorm/xorm/session_schema.go
+++ /dev/null
@@ -1,421 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "fmt"
- "strings"
-
- "xorm.io/core"
-)
-
-// Ping test if database is ok
-func (session *Session) Ping() error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
- return session.DB().PingContext(session.ctx)
-}
-
-// CreateTable create a table according a bean
-func (session *Session) CreateTable(bean interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- return session.createTable(bean)
-}
-
-func (session *Session) createTable(bean interface{}) error {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- sqlStr := session.statement.genCreateTableSQL()
- _, err := session.exec(sqlStr)
- return err
-}
-
-// CreateIndexes create indexes
-func (session *Session) CreateIndexes(bean interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- return session.createIndexes(bean)
-}
-
-func (session *Session) createIndexes(bean interface{}) error {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- sqls := session.statement.genIndexSQL()
- for _, sqlStr := range sqls {
- _, err := session.exec(sqlStr)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// CreateUniques create uniques
-func (session *Session) CreateUniques(bean interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
- return session.createUniques(bean)
-}
-
-func (session *Session) createUniques(bean interface{}) error {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- sqls := session.statement.genUniqueSQL()
- for _, sqlStr := range sqls {
- _, err := session.exec(sqlStr)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// DropIndexes drop indexes
-func (session *Session) DropIndexes(bean interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- return session.dropIndexes(bean)
-}
-
-func (session *Session) dropIndexes(bean interface{}) error {
- if err := session.statement.setRefBean(bean); err != nil {
- return err
- }
-
- sqls := session.statement.genDelIndexSQL()
- for _, sqlStr := range sqls {
- _, err := session.exec(sqlStr)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// DropTable drop table will drop table if exist, if drop failed, it will return error
-func (session *Session) DropTable(beanOrTableName interface{}) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- return session.dropTable(beanOrTableName)
-}
-
-func (session *Session) dropTable(beanOrTableName interface{}) error {
- tableName := session.engine.TableName(beanOrTableName)
- var needDrop = true
- if !session.engine.dialect.SupportDropIfExists() {
- sqlStr, args := session.engine.dialect.TableCheckSql(tableName)
- results, err := session.queryBytes(sqlStr, args...)
- if err != nil {
- return err
- }
- needDrop = len(results) > 0
- }
-
- if needDrop {
- sqlStr := session.engine.Dialect().DropTableSql(session.engine.TableName(tableName, true))
- _, err := session.exec(sqlStr)
- return err
- }
- return nil
-}
-
-// IsTableExist if a table is exist
-func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- tableName := session.engine.TableName(beanOrTableName)
-
- return session.isTableExist(tableName)
-}
-
-func (session *Session) isTableExist(tableName string) (bool, error) {
- sqlStr, args := session.engine.dialect.TableCheckSql(tableName)
- results, err := session.queryBytes(sqlStr, args...)
- return len(results) > 0, err
-}
-
-// IsTableEmpty if table have any records
-func (session *Session) IsTableEmpty(bean interface{}) (bool, error) {
- if session.isAutoClose {
- defer session.Close()
- }
- return session.isTableEmpty(session.engine.TableName(bean))
-}
-
-func (session *Session) isTableEmpty(tableName string) (bool, error) {
- var total int64
- sqlStr := fmt.Sprintf("select count(*) from %s", session.engine.Quote(session.engine.TableName(tableName, true)))
- err := session.queryRow(sqlStr).Scan(&total)
- if err != nil {
- if err == sql.ErrNoRows {
- err = nil
- }
- return true, err
- }
-
- return total == 0, nil
-}
-
-// find if index is exist according cols
-func (session *Session) isIndexExist2(tableName string, cols []string, unique bool) (bool, error) {
- indexes, err := session.engine.dialect.GetIndexes(tableName)
- if err != nil {
- return false, err
- }
-
- for _, index := range indexes {
- if sliceEq(index.Cols, cols) {
- if unique {
- return index.Type == core.UniqueType, nil
- }
- return index.Type == core.IndexType, nil
- }
- }
- return false, nil
-}
-
-func (session *Session) addColumn(colName string) error {
- col := session.statement.RefTable.GetColumn(colName)
- sql, args := session.statement.genAddColumnStr(col)
- _, err := session.exec(sql, args...)
- return err
-}
-
-func (session *Session) addIndex(tableName, idxName string) error {
- index := session.statement.RefTable.Indexes[idxName]
- sqlStr := session.engine.dialect.CreateIndexSql(tableName, index)
- _, err := session.exec(sqlStr)
- return err
-}
-
-func (session *Session) addUnique(tableName, uqeName string) error {
- index := session.statement.RefTable.Indexes[uqeName]
- sqlStr := session.engine.dialect.CreateIndexSql(tableName, index)
- _, err := session.exec(sqlStr)
- return err
-}
-
-// Sync2 synchronize structs to database tables
-func (session *Session) Sync2(beans ...interface{}) error {
- engine := session.engine
-
- if session.isAutoClose {
- session.isAutoClose = false
- defer session.Close()
- }
-
- tables, err := engine.DBMetas()
- if err != nil {
- return err
- }
-
- session.autoResetStatement = false
- defer func() {
- session.autoResetStatement = true
- session.resetStatement()
- }()
-
- var structTables []*core.Table
-
- for _, bean := range beans {
- v := rValue(bean)
- table, err := engine.mapType(v)
- if err != nil {
- return err
- }
- structTables = append(structTables, table)
- tbName := engine.TableName(bean)
- tbNameWithSchema := engine.TableName(tbName, true)
-
- var oriTable *core.Table
- for _, tb := range tables {
- if strings.EqualFold(tb.Name, tbName) {
- oriTable = tb
- break
- }
- }
-
- if oriTable == nil {
- err = session.StoreEngine(session.statement.StoreEngine).createTable(bean)
- if err != nil {
- return err
- }
-
- err = session.createUniques(bean)
- if err != nil {
- return err
- }
-
- err = session.createIndexes(bean)
- if err != nil {
- return err
- }
- } else {
- for _, col := range table.Columns() {
- var oriCol *core.Column
- for _, col2 := range oriTable.Columns() {
- if strings.EqualFold(col.Name, col2.Name) {
- oriCol = col2
- break
- }
- }
-
- if oriCol != nil {
- expectedType := engine.dialect.SqlType(col)
- curType := engine.dialect.SqlType(oriCol)
- if expectedType != curType {
- if expectedType == core.Text &&
- strings.HasPrefix(curType, core.Varchar) {
- // currently only support mysql & postgres
- if engine.dialect.DBType() == core.MYSQL ||
- engine.dialect.DBType() == core.POSTGRES {
- engine.logger.Infof("Table %s column %s change type from %s to %s\n",
- tbNameWithSchema, col.Name, curType, expectedType)
- _, err = session.exec(engine.dialect.ModifyColumnSql(tbNameWithSchema, col))
- } else {
- engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s\n",
- tbNameWithSchema, col.Name, curType, expectedType)
- }
- } else if strings.HasPrefix(curType, core.Varchar) && strings.HasPrefix(expectedType, core.Varchar) {
- if engine.dialect.DBType() == core.MYSQL {
- if oriCol.Length < col.Length {
- engine.logger.Infof("Table %s column %s change type from varchar(%d) to varchar(%d)\n",
- tbNameWithSchema, col.Name, oriCol.Length, col.Length)
- _, err = session.exec(engine.dialect.ModifyColumnSql(tbNameWithSchema, col))
- }
- }
- } else {
- if !(strings.HasPrefix(curType, expectedType) && curType[len(expectedType)] == '(') {
- engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s",
- tbNameWithSchema, col.Name, curType, expectedType)
- }
- }
- } else if expectedType == core.Varchar {
- if engine.dialect.DBType() == core.MYSQL {
- if oriCol.Length < col.Length {
- engine.logger.Infof("Table %s column %s change type from varchar(%d) to varchar(%d)\n",
- tbNameWithSchema, col.Name, oriCol.Length, col.Length)
- _, err = session.exec(engine.dialect.ModifyColumnSql(tbNameWithSchema, col))
- }
- }
- }
- if col.Default != oriCol.Default {
- engine.logger.Warnf("Table %s Column %s db default is %s, struct default is %s",
- tbName, col.Name, oriCol.Default, col.Default)
- }
- if col.Nullable != oriCol.Nullable {
- engine.logger.Warnf("Table %s Column %s db nullable is %v, struct nullable is %v",
- tbName, col.Name, oriCol.Nullable, col.Nullable)
- }
- } else {
- session.statement.RefTable = table
- session.statement.tableName = tbNameWithSchema
- err = session.addColumn(col.Name)
- }
- if err != nil {
- return err
- }
- }
-
- var foundIndexNames = make(map[string]bool)
- var addedNames = make(map[string]*core.Index)
-
- for name, index := range table.Indexes {
- var oriIndex *core.Index
- for name2, index2 := range oriTable.Indexes {
- if index.Equal(index2) {
- oriIndex = index2
- foundIndexNames[name2] = true
- break
- }
- }
-
- if oriIndex != nil {
- if oriIndex.Type != index.Type {
- sql := engine.dialect.DropIndexSql(tbNameWithSchema, oriIndex)
- _, err = session.exec(sql)
- if err != nil {
- return err
- }
- oriIndex = nil
- }
- }
-
- if oriIndex == nil {
- addedNames[name] = index
- }
- }
-
- for name2, index2 := range oriTable.Indexes {
- if _, ok := foundIndexNames[name2]; !ok {
- sql := engine.dialect.DropIndexSql(tbNameWithSchema, index2)
- _, err = session.exec(sql)
- if err != nil {
- return err
- }
- }
- }
-
- for name, index := range addedNames {
- if index.Type == core.UniqueType {
- session.statement.RefTable = table
- session.statement.tableName = tbNameWithSchema
- err = session.addUnique(tbNameWithSchema, name)
- } else if index.Type == core.IndexType {
- session.statement.RefTable = table
- session.statement.tableName = tbNameWithSchema
- err = session.addIndex(tbNameWithSchema, name)
- }
- if err != nil {
- return err
- }
- }
- }
- }
-
- for _, table := range tables {
- var oriTable *core.Table
- for _, structTable := range structTables {
- if strings.EqualFold(table.Name, session.tbNameNoSchema(structTable)) {
- oriTable = structTable
- break
- }
- }
-
- if oriTable == nil {
- //engine.LogWarnf("Table %s has no struct to mapping it", table.Name)
- continue
- }
-
- for _, colName := range table.ColumnsSeq() {
- if oriTable.GetColumn(colName) == nil {
- engine.logger.Warnf("Table %s has column %s but struct has not related field", engine.TableName(table.Name, true), colName)
- }
- }
- }
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_stats.go b/vendor/github.com/go-xorm/xorm/session_stats.go
deleted file mode 100644
index c2cac83..0000000
--- a/vendor/github.com/go-xorm/xorm/session_stats.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql"
- "errors"
- "reflect"
-)
-
-// Count counts the records. bean's non-empty fields
-// are conditions.
-func (session *Session) Count(bean ...interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- var sqlStr string
- var args []interface{}
- var err error
- if session.statement.RawSQL == "" {
- sqlStr, args, err = session.statement.genCountSQL(bean...)
- if err != nil {
- return 0, err
- }
- } else {
- sqlStr = session.statement.RawSQL
- args = session.statement.RawParams
- }
-
- var total int64
- err = session.queryRow(sqlStr, args...).Scan(&total)
- if err == sql.ErrNoRows || err == nil {
- return total, nil
- }
-
- return 0, err
-}
-
-// sum call sum some column. bean's non-empty fields are conditions.
-func (session *Session) sum(res interface{}, bean interface{}, columnNames ...string) error {
- if session.isAutoClose {
- defer session.Close()
- }
-
- v := reflect.ValueOf(res)
- if v.Kind() != reflect.Ptr {
- return errors.New("need a pointer to a variable")
- }
-
- var isSlice = v.Elem().Kind() == reflect.Slice
- var sqlStr string
- var args []interface{}
- var err error
- if len(session.statement.RawSQL) == 0 {
- sqlStr, args, err = session.statement.genSumSQL(bean, columnNames...)
- if err != nil {
- return err
- }
- } else {
- sqlStr = session.statement.RawSQL
- args = session.statement.RawParams
- }
-
- if isSlice {
- err = session.queryRow(sqlStr, args...).ScanSlice(res)
- } else {
- err = session.queryRow(sqlStr, args...).Scan(res)
- }
- if err == sql.ErrNoRows || err == nil {
- return nil
- }
- return err
-}
-
-// Sum call sum some column. bean's non-empty fields are conditions.
-func (session *Session) Sum(bean interface{}, columnName string) (res float64, err error) {
- return res, session.sum(&res, bean, columnName)
-}
-
-// SumInt call sum some column. bean's non-empty fields are conditions.
-func (session *Session) SumInt(bean interface{}, columnName string) (res int64, err error) {
- return res, session.sum(&res, bean, columnName)
-}
-
-// Sums call sum some columns. bean's non-empty fields are conditions.
-func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error) {
- var res = make([]float64, len(columnNames), len(columnNames))
- return res, session.sum(&res, bean, columnNames...)
-}
-
-// SumsInt sum specify columns and return as []int64 instead of []float64
-func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error) {
- var res = make([]int64, len(columnNames), len(columnNames))
- return res, session.sum(&res, bean, columnNames...)
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_tx.go b/vendor/github.com/go-xorm/xorm/session_tx.go
deleted file mode 100644
index ee3d473..0000000
--- a/vendor/github.com/go-xorm/xorm/session_tx.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-// Begin a transaction
-func (session *Session) Begin() error {
- if session.isAutoCommit {
- tx, err := session.DB().BeginTx(session.ctx, nil)
- if err != nil {
- return err
- }
- session.isAutoCommit = false
- session.isCommitedOrRollbacked = false
- session.tx = tx
- session.saveLastSQL("BEGIN TRANSACTION")
- }
- return nil
-}
-
-// Rollback When using transaction, you can rollback if any error
-func (session *Session) Rollback() error {
- if !session.isAutoCommit && !session.isCommitedOrRollbacked {
- session.saveLastSQL(session.engine.dialect.RollBackStr())
- session.isCommitedOrRollbacked = true
- session.isAutoCommit = true
- return session.tx.Rollback()
- }
- return nil
-}
-
-// Commit When using transaction, Commit will commit all operations.
-func (session *Session) Commit() error {
- if !session.isAutoCommit && !session.isCommitedOrRollbacked {
- session.saveLastSQL("COMMIT")
- session.isCommitedOrRollbacked = true
- session.isAutoCommit = true
- var err error
- if err = session.tx.Commit(); err == nil {
- // handle processors after tx committed
- closureCallFunc := func(closuresPtr *[]func(interface{}), bean interface{}) {
- if closuresPtr != nil {
- for _, closure := range *closuresPtr {
- closure(bean)
- }
- }
- }
-
- for bean, closuresPtr := range session.afterInsertBeans {
- closureCallFunc(closuresPtr, bean)
-
- if processor, ok := interface{}(bean).(AfterInsertProcessor); ok {
- processor.AfterInsert()
- }
- }
- for bean, closuresPtr := range session.afterUpdateBeans {
- closureCallFunc(closuresPtr, bean)
-
- if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
- processor.AfterUpdate()
- }
- }
- for bean, closuresPtr := range session.afterDeleteBeans {
- closureCallFunc(closuresPtr, bean)
-
- if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
- processor.AfterDelete()
- }
- }
- cleanUpFunc := func(slices *map[interface{}]*[]func(interface{})) {
- if len(*slices) > 0 {
- *slices = make(map[interface{}]*[]func(interface{}), 0)
- }
- }
- cleanUpFunc(&session.afterInsertBeans)
- cleanUpFunc(&session.afterUpdateBeans)
- cleanUpFunc(&session.afterDeleteBeans)
- }
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/session_update.go b/vendor/github.com/go-xorm/xorm/session_update.go
deleted file mode 100644
index 216c4e8..0000000
--- a/vendor/github.com/go-xorm/xorm/session_update.go
+++ /dev/null
@@ -1,511 +0,0 @@
-// Copyright 2016 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "strings"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-func (session *Session) cacheUpdate(table *core.Table, tableName, sqlStr string, args ...interface{}) error {
- if table == nil ||
- session.tx != nil {
- return ErrCacheFailed
- }
-
- oldhead, newsql := session.statement.convertUpdateSQL(sqlStr)
- if newsql == "" {
- return ErrCacheFailed
- }
- for _, filter := range session.engine.dialect.Filters() {
- newsql = filter.Do(newsql, session.engine.dialect, table)
- }
- session.engine.logger.Debug("[cacheUpdate] new sql", oldhead, newsql)
-
- var nStart int
- if len(args) > 0 {
- if strings.Index(sqlStr, "?") > -1 {
- nStart = strings.Count(oldhead, "?")
- } else {
- // only for pq, TODO: if any other databse?
- nStart = strings.Count(oldhead, "$")
- }
- }
-
- cacher := session.engine.getCacher(tableName)
- session.engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:])
- ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:])
- if err != nil {
- rows, err := session.NoCache().queryRows(newsql, args[nStart:]...)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- ids = make([]core.PK, 0)
- for rows.Next() {
- var res = make([]string, len(table.PrimaryKeys))
- err = rows.ScanSlice(&res)
- if err != nil {
- return err
- }
- var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
- for i, col := range table.PKColumns() {
- if col.SQLType.IsNumeric() {
- n, err := strconv.ParseInt(res[i], 10, 64)
- if err != nil {
- return err
- }
- pk[i] = n
- } else if col.SQLType.IsText() {
- pk[i] = res[i]
- } else {
- return errors.New("not supported")
- }
- }
-
- ids = append(ids, pk)
- }
- session.engine.logger.Debug("[cacheUpdate] find updated id", ids)
- } /*else {
- session.engine.LogDebug("[xorm:cacheUpdate] del cached sql:", tableName, newsql, args)
- cacher.DelIds(tableName, genSqlKey(newsql, args))
- }*/
-
- for _, id := range ids {
- sid, err := id.ToString()
- if err != nil {
- return err
- }
- if bean := cacher.GetBean(tableName, sid); bean != nil {
- sqls := splitNNoCase(sqlStr, "where", 2)
- if len(sqls) == 0 || len(sqls) > 2 {
- return ErrCacheFailed
- }
-
- sqls = splitNNoCase(sqls[0], "set", 2)
- if len(sqls) != 2 {
- return ErrCacheFailed
- }
- kvs := strings.Split(strings.TrimSpace(sqls[1]), ",")
- for idx, kv := range kvs {
- sps := strings.SplitN(kv, "=", 2)
- sps2 := strings.Split(sps[0], ".")
- colName := sps2[len(sps2)-1]
- if strings.Contains(colName, "`") {
- colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1))
- } else if strings.Contains(colName, session.engine.QuoteStr()) {
- colName = strings.TrimSpace(strings.Replace(colName, session.engine.QuoteStr(), "", -1))
- } else {
- session.engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName)
- return ErrCacheFailed
- }
-
- if col := table.GetColumn(colName); col != nil {
- fieldValue, err := col.ValueOf(bean)
- if err != nil {
- session.engine.logger.Error(err)
- } else {
- session.engine.logger.Debug("[cacheUpdate] set bean field", bean, colName, fieldValue.Interface())
- if col.IsVersion && session.statement.checkVersion {
- session.incrVersionFieldValue(fieldValue)
- } else {
- fieldValue.Set(reflect.ValueOf(args[idx]))
- }
- }
- } else {
- session.engine.logger.Errorf("[cacheUpdate] ERROR: column %v is not table %v's",
- colName, table.Name)
- }
- }
-
- session.engine.logger.Debug("[cacheUpdate] update cache", tableName, id, bean)
- cacher.PutBean(tableName, sid, bean)
- }
- }
- session.engine.logger.Debug("[cacheUpdate] clear cached table sql:", tableName)
- cacher.ClearIds(tableName)
- return nil
-}
-
-// Update records, bean's non-empty fields are updated contents,
-// condiBean' non-empty filds are conditions
-// CAUTION:
-// 1.bool will defaultly be updated content nor conditions
-// You should call UseBool if you have bool to use.
-// 2.float32 & float64 may be not inexact as conditions
-func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
- if session.isAutoClose {
- defer session.Close()
- }
-
- if session.statement.lastError != nil {
- return 0, session.statement.lastError
- }
-
- v := rValue(bean)
- t := v.Type()
-
- var colNames []string
- var args []interface{}
-
- // handle before update processors
- for _, closure := range session.beforeClosures {
- closure(bean)
- }
- cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
- if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok {
- processor.BeforeUpdate()
- }
- // --
-
- var err error
- var isMap = t.Kind() == reflect.Map
- var isStruct = t.Kind() == reflect.Struct
- if isStruct {
- if err := session.statement.setRefBean(bean); err != nil {
- return 0, err
- }
-
- if len(session.statement.TableName()) <= 0 {
- return 0, ErrTableNotFound
- }
-
- if session.statement.ColumnStr == "" {
- colNames, args = session.statement.buildUpdates(bean, false, false,
- false, false, true)
- } else {
- colNames, args, err = session.genUpdateColumns(bean)
- if err != nil {
- return 0, err
- }
- }
- } else if isMap {
- colNames = make([]string, 0)
- args = make([]interface{}, 0)
- bValue := reflect.Indirect(reflect.ValueOf(bean))
-
- for _, v := range bValue.MapKeys() {
- colNames = append(colNames, session.engine.Quote(v.String())+" = ?")
- args = append(args, bValue.MapIndex(v).Interface())
- }
- } else {
- return 0, ErrParamsType
- }
-
- table := session.statement.RefTable
-
- if session.statement.UseAutoTime && table != nil && table.Updated != "" {
- if !session.statement.columnMap.contain(table.Updated) &&
- !session.statement.omitColumnMap.contain(table.Updated) {
- colNames = append(colNames, session.engine.Quote(table.Updated)+" = ?")
- col := table.UpdatedColumn()
- val, t := session.engine.nowTime(col)
- args = append(args, val)
-
- var colName = col.Name
- if isStruct {
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- }
- }
- }
-
- //for update action to like "column = column + ?"
- incColumns := session.statement.getInc()
- for _, v := range incColumns {
- colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" + ?")
- args = append(args, v.arg)
- }
- //for update action to like "column = column - ?"
- decColumns := session.statement.getDec()
- for _, v := range decColumns {
- colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" - ?")
- args = append(args, v.arg)
- }
- //for update action to like "column = expression"
- exprColumns := session.statement.getExpr()
- for _, v := range exprColumns {
- colNames = append(colNames, session.engine.Quote(v.colName)+" = "+v.expr)
- }
-
- if err = session.statement.processIDParam(); err != nil {
- return 0, err
- }
-
- var autoCond builder.Cond
- if !session.statement.noAutoCondition {
- condBeanIsStruct := false
- if len(condiBean) > 0 {
- if c, ok := condiBean[0].(map[string]interface{}); ok {
- autoCond = builder.Eq(c)
- } else {
- ct := reflect.TypeOf(condiBean[0])
- k := ct.Kind()
- if k == reflect.Ptr {
- k = ct.Elem().Kind()
- }
- if k == reflect.Struct {
- var err error
- autoCond, err = session.statement.buildConds(session.statement.RefTable, condiBean[0], true, true, false, true, false)
- if err != nil {
- return 0, err
- }
- condBeanIsStruct = true
- } else {
- return 0, ErrConditionType
- }
- }
- }
-
- if !condBeanIsStruct && table != nil {
- if col := table.DeletedColumn(); col != nil && !session.statement.unscoped { // tag "deleted" is enabled
- autoCond1 := session.engine.CondDeleted(session.engine.Quote(col.Name))
-
- if autoCond == nil {
- autoCond = autoCond1
- } else {
- autoCond = autoCond.And(autoCond1)
- }
- }
- }
- }
-
- st := &session.statement
-
- var sqlStr string
- var condArgs []interface{}
- var condSQL string
- cond := session.statement.cond.And(autoCond)
-
- var doIncVer = (table != nil && table.Version != "" && session.statement.checkVersion)
- var verValue *reflect.Value
- if doIncVer {
- verValue, err = table.VersionColumn().ValueOf(bean)
- if err != nil {
- return 0, err
- }
-
- cond = cond.And(builder.Eq{session.engine.Quote(table.Version): verValue.Interface()})
- colNames = append(colNames, session.engine.Quote(table.Version)+" = "+session.engine.Quote(table.Version)+" + 1")
- }
-
- condSQL, condArgs, err = builder.ToSQL(cond)
- if err != nil {
- return 0, err
- }
-
- if len(condSQL) > 0 {
- condSQL = "WHERE " + condSQL
- }
-
- if st.OrderStr != "" {
- condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
- }
-
- var tableName = session.statement.TableName()
- // TODO: Oracle support needed
- var top string
- if st.LimitN > 0 {
- if st.Engine.dialect.DBType() == core.MYSQL {
- condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
- } else if st.Engine.dialect.DBType() == core.SQLITE {
- tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
- cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
- session.engine.Quote(tableName), tempCondSQL), condArgs...))
- condSQL, condArgs, err = builder.ToSQL(cond)
- if err != nil {
- return 0, err
- }
- if len(condSQL) > 0 {
- condSQL = "WHERE " + condSQL
- }
- } else if st.Engine.dialect.DBType() == core.POSTGRES {
- tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
- cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
- session.engine.Quote(tableName), tempCondSQL), condArgs...))
- condSQL, condArgs, err = builder.ToSQL(cond)
- if err != nil {
- return 0, err
- }
-
- if len(condSQL) > 0 {
- condSQL = "WHERE " + condSQL
- }
- } else if st.Engine.dialect.DBType() == core.MSSQL {
- if st.OrderStr != "" && st.Engine.dialect.DBType() == core.MSSQL &&
- table != nil && len(table.PrimaryKeys) == 1 {
- cond = builder.Expr(fmt.Sprintf("%s IN (SELECT TOP (%d) %s FROM %v%v)",
- table.PrimaryKeys[0], st.LimitN, table.PrimaryKeys[0],
- session.engine.Quote(tableName), condSQL), condArgs...)
-
- condSQL, condArgs, err = builder.ToSQL(cond)
- if err != nil {
- return 0, err
- }
- if len(condSQL) > 0 {
- condSQL = "WHERE " + condSQL
- }
- } else {
- top = fmt.Sprintf("TOP (%d) ", st.LimitN)
- }
- }
- }
-
- if len(colNames) <= 0 {
- return 0, errors.New("No content found to be updated")
- }
-
- sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v",
- top,
- session.engine.Quote(tableName),
- strings.Join(colNames, ", "),
- condSQL)
-
- res, err := session.exec(sqlStr, append(args, condArgs...)...)
- if err != nil {
- return 0, err
- } else if doIncVer {
- if verValue != nil && verValue.IsValid() && verValue.CanSet() {
- session.incrVersionFieldValue(verValue)
- }
- }
-
- if cacher := session.engine.getCacher(tableName); cacher != nil && session.statement.UseCache {
- //session.cacheUpdate(table, tableName, sqlStr, args...)
- session.engine.logger.Debug("[cacheUpdate] clear table ", tableName)
- cacher.ClearIds(tableName)
- cacher.ClearBeans(tableName)
- }
-
- // handle after update processors
- if session.isAutoCommit {
- for _, closure := range session.afterClosures {
- closure(bean)
- }
- if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
- session.engine.logger.Debug("[event]", tableName, " has after update processor")
- processor.AfterUpdate()
- }
- } else {
- lenAfterClosures := len(session.afterClosures)
- if lenAfterClosures > 0 {
- if value, has := session.afterUpdateBeans[bean]; has && value != nil {
- *value = append(*value, session.afterClosures...)
- } else {
- afterClosures := make([]func(interface{}), lenAfterClosures)
- copy(afterClosures, session.afterClosures)
- // FIXME: if bean is a map type, it will panic because map cannot be as map key
- session.afterUpdateBeans[bean] = &afterClosures
- }
-
- } else {
- if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
- session.afterUpdateBeans[bean] = nil
- }
- }
- }
- cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
- // --
-
- return res.RowsAffected()
-}
-
-func (session *Session) genUpdateColumns(bean interface{}) ([]string, []interface{}, error) {
- table := session.statement.RefTable
- colNames := make([]string, 0, len(table.ColumnsSeq()))
- args := make([]interface{}, 0, len(table.ColumnsSeq()))
-
- for _, col := range table.Columns() {
- if !col.IsVersion && !col.IsCreated && !col.IsUpdated {
- if session.statement.omitColumnMap.contain(col.Name) {
- continue
- }
- }
- if col.MapType == core.ONLYFROMDB {
- continue
- }
-
- fieldValuePtr, err := col.ValueOf(bean)
- if err != nil {
- return nil, nil, err
- }
- fieldValue := *fieldValuePtr
-
- if col.IsAutoIncrement {
- switch fieldValue.Type().Kind() {
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
- if fieldValue.Int() == 0 {
- continue
- }
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
- if fieldValue.Uint() == 0 {
- continue
- }
- case reflect.String:
- if len(fieldValue.String()) == 0 {
- continue
- }
- case reflect.Ptr:
- if fieldValue.Pointer() == 0 {
- continue
- }
- }
- }
-
- if (col.IsDeleted && !session.statement.unscoped) || col.IsCreated {
- continue
- }
-
- if len(session.statement.columnMap) > 0 {
- if !session.statement.columnMap.contain(col.Name) {
- continue
- } else if _, ok := session.statement.incrColumns[col.Name]; ok {
- continue
- } else if _, ok := session.statement.decrColumns[col.Name]; ok {
- continue
- }
- }
-
- // !evalphobia! set fieldValue as nil when column is nullable and zero-value
- if _, ok := getFlagForColumn(session.statement.nullableMap, col); ok {
- if col.Nullable && isZero(fieldValue.Interface()) {
- var nilValue *int
- fieldValue = reflect.ValueOf(nilValue)
- }
- }
-
- if col.IsUpdated && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
- // if time is non-empty, then set to auto time
- val, t := session.engine.nowTime(col)
- args = append(args, val)
-
- var colName = col.Name
- session.afterClosures = append(session.afterClosures, func(bean interface{}) {
- col := table.GetColumn(colName)
- setColumnTime(bean, col, t)
- })
- } else if col.IsVersion && session.statement.checkVersion {
- args = append(args, 1)
- } else {
- arg, err := session.value2Interface(col, fieldValue)
- if err != nil {
- return colNames, args, err
- }
- args = append(args, arg)
- }
-
- colNames = append(colNames, session.engine.Quote(col.Name)+" = ?")
- }
- return colNames, args, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/statement.go b/vendor/github.com/go-xorm/xorm/statement.go
deleted file mode 100644
index 88b8423..0000000
--- a/vendor/github.com/go-xorm/xorm/statement.go
+++ /dev/null
@@ -1,1267 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "database/sql/driver"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "time"
-
- "xorm.io/builder"
- "xorm.io/core"
-)
-
-// Statement save all the sql info for executing SQL
-type Statement struct {
- RefTable *core.Table
- Engine *Engine
- Start int
- LimitN int
- idParam *core.PK
- OrderStr string
- JoinStr string
- joinArgs []interface{}
- GroupByStr string
- HavingStr string
- ColumnStr string
- selectStr string
- useAllCols bool
- OmitStr string
- AltTableName string
- tableName string
- RawSQL string
- RawParams []interface{}
- UseCascade bool
- UseAutoJoin bool
- StoreEngine string
- Charset string
- UseCache bool
- UseAutoTime bool
- noAutoCondition bool
- IsDistinct bool
- IsForUpdate bool
- TableAlias string
- allUseBool bool
- checkVersion bool
- unscoped bool
- columnMap columnMap
- omitColumnMap columnMap
- mustColumnMap map[string]bool
- nullableMap map[string]bool
- incrColumns map[string]incrParam
- decrColumns map[string]decrParam
- exprColumns map[string]exprParam
- cond builder.Cond
- bufferSize int
- context ContextCache
- lastError error
-}
-
-// Init reset all the statement's fields
-func (statement *Statement) Init() {
- statement.RefTable = nil
- statement.Start = 0
- statement.LimitN = 0
- statement.OrderStr = ""
- statement.UseCascade = true
- statement.JoinStr = ""
- statement.joinArgs = make([]interface{}, 0)
- statement.GroupByStr = ""
- statement.HavingStr = ""
- statement.ColumnStr = ""
- statement.OmitStr = ""
- statement.columnMap = columnMap{}
- statement.omitColumnMap = columnMap{}
- statement.AltTableName = ""
- statement.tableName = ""
- statement.idParam = nil
- statement.RawSQL = ""
- statement.RawParams = make([]interface{}, 0)
- statement.UseCache = true
- statement.UseAutoTime = true
- statement.noAutoCondition = false
- statement.IsDistinct = false
- statement.IsForUpdate = false
- statement.TableAlias = ""
- statement.selectStr = ""
- statement.allUseBool = false
- statement.useAllCols = false
- statement.mustColumnMap = make(map[string]bool)
- statement.nullableMap = make(map[string]bool)
- statement.checkVersion = true
- statement.unscoped = false
- statement.incrColumns = make(map[string]incrParam)
- statement.decrColumns = make(map[string]decrParam)
- statement.exprColumns = make(map[string]exprParam)
- statement.cond = builder.NewCond()
- statement.bufferSize = 0
- statement.context = nil
- statement.lastError = nil
-}
-
-// NoAutoCondition if you do not want convert bean's field as query condition, then use this function
-func (statement *Statement) NoAutoCondition(no ...bool) *Statement {
- statement.noAutoCondition = true
- if len(no) > 0 {
- statement.noAutoCondition = no[0]
- }
- return statement
-}
-
-// Alias set the table alias
-func (statement *Statement) Alias(alias string) *Statement {
- statement.TableAlias = alias
- return statement
-}
-
-// SQL adds raw sql statement
-func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement {
- switch query.(type) {
- case (*builder.Builder):
- var err error
- statement.RawSQL, statement.RawParams, err = query.(*builder.Builder).ToSQL()
- if err != nil {
- statement.lastError = err
- }
- case string:
- statement.RawSQL = query.(string)
- statement.RawParams = args
- default:
- statement.lastError = ErrUnSupportedSQLType
- }
-
- return statement
-}
-
-// Where add Where statement
-func (statement *Statement) Where(query interface{}, args ...interface{}) *Statement {
- return statement.And(query, args...)
-}
-
-// And add Where & and statement
-func (statement *Statement) And(query interface{}, args ...interface{}) *Statement {
- switch query.(type) {
- case string:
- cond := builder.Expr(query.(string), args...)
- statement.cond = statement.cond.And(cond)
- case map[string]interface{}:
- cond := builder.Eq(query.(map[string]interface{}))
- statement.cond = statement.cond.And(cond)
- case builder.Cond:
- cond := query.(builder.Cond)
- statement.cond = statement.cond.And(cond)
- for _, v := range args {
- if vv, ok := v.(builder.Cond); ok {
- statement.cond = statement.cond.And(vv)
- }
- }
- default:
- statement.lastError = ErrConditionType
- }
-
- return statement
-}
-
-// Or add Where & Or statement
-func (statement *Statement) Or(query interface{}, args ...interface{}) *Statement {
- switch query.(type) {
- case string:
- cond := builder.Expr(query.(string), args...)
- statement.cond = statement.cond.Or(cond)
- case map[string]interface{}:
- cond := builder.Eq(query.(map[string]interface{}))
- statement.cond = statement.cond.Or(cond)
- case builder.Cond:
- cond := query.(builder.Cond)
- statement.cond = statement.cond.Or(cond)
- for _, v := range args {
- if vv, ok := v.(builder.Cond); ok {
- statement.cond = statement.cond.Or(vv)
- }
- }
- default:
- // TODO: not support condition type
- }
- return statement
-}
-
-// In generate "Where column IN (?) " statement
-func (statement *Statement) In(column string, args ...interface{}) *Statement {
- in := builder.In(statement.Engine.Quote(column), args...)
- statement.cond = statement.cond.And(in)
- return statement
-}
-
-// NotIn generate "Where column NOT IN (?) " statement
-func (statement *Statement) NotIn(column string, args ...interface{}) *Statement {
- notIn := builder.NotIn(statement.Engine.Quote(column), args...)
- statement.cond = statement.cond.And(notIn)
- return statement
-}
-
-func (statement *Statement) setRefValue(v reflect.Value) error {
- var err error
- statement.RefTable, err = statement.Engine.autoMapType(reflect.Indirect(v))
- if err != nil {
- return err
- }
- statement.tableName = statement.Engine.TableName(v, true)
- return nil
-}
-
-func (statement *Statement) setRefBean(bean interface{}) error {
- var err error
- statement.RefTable, err = statement.Engine.autoMapType(rValue(bean))
- if err != nil {
- return err
- }
- statement.tableName = statement.Engine.TableName(bean, true)
- return nil
-}
-
-// Auto generating update columnes and values according a struct
-func (statement *Statement) buildUpdates(bean interface{},
- includeVersion, includeUpdated, includeNil,
- includeAutoIncr, update bool) ([]string, []interface{}) {
- engine := statement.Engine
- table := statement.RefTable
- allUseBool := statement.allUseBool
- useAllCols := statement.useAllCols
- mustColumnMap := statement.mustColumnMap
- nullableMap := statement.nullableMap
- columnMap := statement.columnMap
- omitColumnMap := statement.omitColumnMap
- unscoped := statement.unscoped
-
- var colNames = make([]string, 0)
- var args = make([]interface{}, 0)
- for _, col := range table.Columns() {
- if !includeVersion && col.IsVersion {
- continue
- }
- if col.IsCreated {
- continue
- }
- if !includeUpdated && col.IsUpdated {
- continue
- }
- if !includeAutoIncr && col.IsAutoIncrement {
- continue
- }
- if col.IsDeleted && !unscoped {
- continue
- }
- if omitColumnMap.contain(col.Name) {
- continue
- }
- if len(columnMap) > 0 && !columnMap.contain(col.Name) {
- continue
- }
-
- if col.MapType == core.ONLYFROMDB {
- continue
- }
-
- fieldValuePtr, err := col.ValueOf(bean)
- if err != nil {
- engine.logger.Error(err)
- continue
- }
-
- fieldValue := *fieldValuePtr
- fieldType := reflect.TypeOf(fieldValue.Interface())
- if fieldType == nil {
- continue
- }
-
- requiredField := useAllCols
- includeNil := useAllCols
-
- if b, ok := getFlagForColumn(mustColumnMap, col); ok {
- if b {
- requiredField = true
- } else {
- continue
- }
- }
-
- // !evalphobia! set fieldValue as nil when column is nullable and zero-value
- if b, ok := getFlagForColumn(nullableMap, col); ok {
- if b && col.Nullable && isZero(fieldValue.Interface()) {
- var nilValue *int
- fieldValue = reflect.ValueOf(nilValue)
- fieldType = reflect.TypeOf(fieldValue.Interface())
- includeNil = true
- }
- }
-
- var val interface{}
-
- if fieldValue.CanAddr() {
- if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
- data, err := structConvert.ToDB()
- if err != nil {
- engine.logger.Error(err)
- } else {
- val = data
- }
- goto APPEND
- }
- }
-
- if structConvert, ok := fieldValue.Interface().(core.Conversion); ok {
- data, err := structConvert.ToDB()
- if err != nil {
- engine.logger.Error(err)
- } else {
- val = data
- }
- goto APPEND
- }
-
- if fieldType.Kind() == reflect.Ptr {
- if fieldValue.IsNil() {
- if includeNil {
- args = append(args, nil)
- colNames = append(colNames, fmt.Sprintf("%v=?", engine.Quote(col.Name)))
- }
- continue
- } else if !fieldValue.IsValid() {
- continue
- } else {
- // dereference ptr type to instance type
- fieldValue = fieldValue.Elem()
- fieldType = reflect.TypeOf(fieldValue.Interface())
- requiredField = true
- }
- }
-
- switch fieldType.Kind() {
- case reflect.Bool:
- if allUseBool || requiredField {
- val = fieldValue.Interface()
- } else {
- // if a bool in a struct, it will not be as a condition because it default is false,
- // please use Where() instead
- continue
- }
- case reflect.String:
- if !requiredField && fieldValue.String() == "" {
- continue
- }
- // for MyString, should convert to string or panic
- if fieldType.String() != reflect.String.String() {
- val = fieldValue.String()
- } else {
- val = fieldValue.Interface()
- }
- case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64:
- if !requiredField && fieldValue.Int() == 0 {
- continue
- }
- val = fieldValue.Interface()
- case reflect.Float32, reflect.Float64:
- if !requiredField && fieldValue.Float() == 0.0 {
- continue
- }
- val = fieldValue.Interface()
- case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
- if !requiredField && fieldValue.Uint() == 0 {
- continue
- }
- t := int64(fieldValue.Uint())
- val = reflect.ValueOf(&t).Interface()
- case reflect.Struct:
- if fieldType.ConvertibleTo(core.TimeType) {
- t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
- if !requiredField && (t.IsZero() || !fieldValue.IsValid()) {
- continue
- }
- val = engine.formatColTime(col, t)
- } else if nulType, ok := fieldValue.Interface().(driver.Valuer); ok {
- val, _ = nulType.Value()
- } else {
- if !col.SQLType.IsJson() {
- engine.autoMapType(fieldValue)
- if table, ok := engine.Tables[fieldValue.Type()]; ok {
- if len(table.PrimaryKeys) == 1 {
- pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName)
- // fix non-int pk issues
- if pkField.IsValid() && (!requiredField && !isZero(pkField.Interface())) {
- val = pkField.Interface()
- } else {
- continue
- }
- } else {
- //TODO: how to handler?
- panic("not supported")
- }
- } else {
- val = fieldValue.Interface()
- }
- } else {
- // Blank struct could not be as update data
- if requiredField || !isStructZero(fieldValue) {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
- }
- if col.SQLType.IsText() {
- val = string(bytes)
- } else if col.SQLType.IsBlob() {
- val = bytes
- }
- } else {
- continue
- }
- }
- }
- case reflect.Array, reflect.Slice, reflect.Map:
- if !requiredField {
- if fieldValue == reflect.Zero(fieldType) {
- continue
- }
- if fieldType.Kind() == reflect.Array {
- if isArrayValueZero(fieldValue) {
- continue
- }
- } else if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 {
- continue
- }
- }
-
- if col.SQLType.IsText() {
- bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = string(bytes)
- } else if col.SQLType.IsBlob() {
- var bytes []byte
- var err error
- if fieldType.Kind() == reflect.Slice &&
- fieldType.Elem().Kind() == reflect.Uint8 {
- if fieldValue.Len() > 0 {
- val = fieldValue.Bytes()
- } else {
- continue
- }
- } else if fieldType.Kind() == reflect.Array &&
- fieldType.Elem().Kind() == reflect.Uint8 {
- val = fieldValue.Slice(0, 0).Interface()
- } else {
- bytes, err = DefaultJSONHandler.Marshal(fieldValue.Interface())
- if err != nil {
- engine.logger.Error(err)
- continue
- }
- val = bytes
- }
- } else {
- continue
- }
- default:
- val = fieldValue.Interface()
- }
-
- APPEND:
- args = append(args, val)
- if col.IsPrimaryKey && engine.dialect.DBType() == "ql" {
- continue
- }
- colNames = append(colNames, fmt.Sprintf("%v = ?", engine.Quote(col.Name)))
- }
-
- return colNames, args
-}
-
-func (statement *Statement) needTableName() bool {
- return len(statement.JoinStr) > 0
-}
-
-func (statement *Statement) colName(col *core.Column, tableName string) string {
- if statement.needTableName() {
- var nm = tableName
- if len(statement.TableAlias) > 0 {
- nm = statement.TableAlias
- }
- return statement.Engine.Quote(nm) + "." + statement.Engine.Quote(col.Name)
- }
- return statement.Engine.Quote(col.Name)
-}
-
-// TableName return current tableName
-func (statement *Statement) TableName() string {
- if statement.AltTableName != "" {
- return statement.AltTableName
- }
-
- return statement.tableName
-}
-
-// ID generate "where id = ? " statement or for composite key "where key1 = ? and key2 = ?"
-func (statement *Statement) ID(id interface{}) *Statement {
- idValue := reflect.ValueOf(id)
- idType := reflect.TypeOf(idValue.Interface())
-
- switch idType {
- case ptrPkType:
- if pkPtr, ok := (id).(*core.PK); ok {
- statement.idParam = pkPtr
- return statement
- }
- case pkType:
- if pk, ok := (id).(core.PK); ok {
- statement.idParam = &pk
- return statement
- }
- }
-
- switch idType.Kind() {
- case reflect.String:
- statement.idParam = &core.PK{idValue.Convert(reflect.TypeOf("")).Interface()}
- return statement
- }
-
- statement.idParam = &core.PK{id}
- return statement
-}
-
-// Incr Generate "Update ... Set column = column + arg" statement
-func (statement *Statement) Incr(column string, arg ...interface{}) *Statement {
- k := strings.ToLower(column)
- if len(arg) > 0 {
- statement.incrColumns[k] = incrParam{column, arg[0]}
- } else {
- statement.incrColumns[k] = incrParam{column, 1}
- }
- return statement
-}
-
-// Decr Generate "Update ... Set column = column - arg" statement
-func (statement *Statement) Decr(column string, arg ...interface{}) *Statement {
- k := strings.ToLower(column)
- if len(arg) > 0 {
- statement.decrColumns[k] = decrParam{column, arg[0]}
- } else {
- statement.decrColumns[k] = decrParam{column, 1}
- }
- return statement
-}
-
-// SetExpr Generate "Update ... Set column = {expression}" statement
-func (statement *Statement) SetExpr(column string, expression string) *Statement {
- k := strings.ToLower(column)
- statement.exprColumns[k] = exprParam{column, expression}
- return statement
-}
-
-// Generate "Update ... Set column = column + arg" statement
-func (statement *Statement) getInc() map[string]incrParam {
- return statement.incrColumns
-}
-
-// Generate "Update ... Set column = column - arg" statement
-func (statement *Statement) getDec() map[string]decrParam {
- return statement.decrColumns
-}
-
-// Generate "Update ... Set column = {expression}" statement
-func (statement *Statement) getExpr() map[string]exprParam {
- return statement.exprColumns
-}
-
-func (statement *Statement) col2NewColsWithQuote(columns ...string) []string {
- newColumns := make([]string, 0)
- for _, col := range columns {
- col = strings.Replace(col, "`", "", -1)
- col = strings.Replace(col, statement.Engine.QuoteStr(), "", -1)
- ccols := strings.Split(col, ",")
- for _, c := range ccols {
- fields := strings.Split(strings.TrimSpace(c), ".")
- if len(fields) == 1 {
- newColumns = append(newColumns, statement.Engine.quote(fields[0]))
- } else if len(fields) == 2 {
- newColumns = append(newColumns, statement.Engine.quote(fields[0])+"."+
- statement.Engine.quote(fields[1]))
- } else {
- panic(errors.New("unwanted colnames"))
- }
- }
- }
- return newColumns
-}
-
-func (statement *Statement) colmap2NewColsWithQuote() []string {
- newColumns := make([]string, len(statement.columnMap), len(statement.columnMap))
- copy(newColumns, statement.columnMap)
- for i := 0; i < len(statement.columnMap); i++ {
- newColumns[i] = statement.Engine.Quote(newColumns[i])
- }
- return newColumns
-}
-
-// Distinct generates "DISTINCT col1, col2 " statement
-func (statement *Statement) Distinct(columns ...string) *Statement {
- statement.IsDistinct = true
- statement.Cols(columns...)
- return statement
-}
-
-// ForUpdate generates "SELECT ... FOR UPDATE" statement
-func (statement *Statement) ForUpdate() *Statement {
- statement.IsForUpdate = true
- return statement
-}
-
-// Select replace select
-func (statement *Statement) Select(str string) *Statement {
- statement.selectStr = str
- return statement
-}
-
-// Cols generate "col1, col2" statement
-func (statement *Statement) Cols(columns ...string) *Statement {
- cols := col2NewCols(columns...)
- for _, nc := range cols {
- statement.columnMap.add(nc)
- }
-
- newColumns := statement.colmap2NewColsWithQuote()
-
- statement.ColumnStr = strings.Join(newColumns, ", ")
- statement.ColumnStr = strings.Replace(statement.ColumnStr, statement.Engine.quote("*"), "*", -1)
- return statement
-}
-
-// AllCols update use only: update all columns
-func (statement *Statement) AllCols() *Statement {
- statement.useAllCols = true
- return statement
-}
-
-// MustCols update use only: must update columns
-func (statement *Statement) MustCols(columns ...string) *Statement {
- newColumns := col2NewCols(columns...)
- for _, nc := range newColumns {
- statement.mustColumnMap[strings.ToLower(nc)] = true
- }
- return statement
-}
-
-// UseBool indicates that use bool fields as update contents and query contiditions
-func (statement *Statement) UseBool(columns ...string) *Statement {
- if len(columns) > 0 {
- statement.MustCols(columns...)
- } else {
- statement.allUseBool = true
- }
- return statement
-}
-
-// Omit do not use the columns
-func (statement *Statement) Omit(columns ...string) {
- newColumns := col2NewCols(columns...)
- for _, nc := range newColumns {
- statement.omitColumnMap = append(statement.omitColumnMap, nc)
- }
- statement.OmitStr = statement.Engine.Quote(strings.Join(newColumns, statement.Engine.Quote(", ")))
-}
-
-// Nullable Update use only: update columns to null when value is nullable and zero-value
-func (statement *Statement) Nullable(columns ...string) {
- newColumns := col2NewCols(columns...)
- for _, nc := range newColumns {
- statement.nullableMap[strings.ToLower(nc)] = true
- }
-}
-
-// Top generate LIMIT limit statement
-func (statement *Statement) Top(limit int) *Statement {
- statement.Limit(limit)
- return statement
-}
-
-// Limit generate LIMIT start, limit statement
-func (statement *Statement) Limit(limit int, start ...int) *Statement {
- statement.LimitN = limit
- if len(start) > 0 {
- statement.Start = start[0]
- }
- return statement
-}
-
-// OrderBy generate "Order By order" statement
-func (statement *Statement) OrderBy(order string) *Statement {
- if len(statement.OrderStr) > 0 {
- statement.OrderStr += ", "
- }
- statement.OrderStr += order
- return statement
-}
-
-// Desc generate `ORDER BY xx DESC`
-func (statement *Statement) Desc(colNames ...string) *Statement {
- var buf builder.StringBuilder
- if len(statement.OrderStr) > 0 {
- fmt.Fprint(&buf, statement.OrderStr, ", ")
- }
- newColNames := statement.col2NewColsWithQuote(colNames...)
- fmt.Fprintf(&buf, "%v DESC", strings.Join(newColNames, " DESC, "))
- statement.OrderStr = buf.String()
- return statement
-}
-
-// Asc provide asc order by query condition, the input parameters are columns.
-func (statement *Statement) Asc(colNames ...string) *Statement {
- var buf builder.StringBuilder
- if len(statement.OrderStr) > 0 {
- fmt.Fprint(&buf, statement.OrderStr, ", ")
- }
- newColNames := statement.col2NewColsWithQuote(colNames...)
- fmt.Fprintf(&buf, "%v ASC", strings.Join(newColNames, " ASC, "))
- statement.OrderStr = buf.String()
- return statement
-}
-
-// Table tempororily set table name, the parameter could be a string or a pointer of struct
-func (statement *Statement) Table(tableNameOrBean interface{}) *Statement {
- v := rValue(tableNameOrBean)
- t := v.Type()
- if t.Kind() == reflect.Struct {
- var err error
- statement.RefTable, err = statement.Engine.autoMapType(v)
- if err != nil {
- statement.Engine.logger.Error(err)
- return statement
- }
- }
-
- statement.AltTableName = statement.Engine.TableName(tableNameOrBean, true)
- return statement
-}
-
-// Join The joinOP should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
-func (statement *Statement) Join(joinOP string, tablename interface{}, condition string, args ...interface{}) *Statement {
- var buf builder.StringBuilder
- if len(statement.JoinStr) > 0 {
- fmt.Fprintf(&buf, "%v %v JOIN ", statement.JoinStr, joinOP)
- } else {
- fmt.Fprintf(&buf, "%v JOIN ", joinOP)
- }
-
- switch tp := tablename.(type) {
- case builder.Builder:
- subSQL, subQueryArgs, err := tp.ToSQL()
- if err != nil {
- statement.lastError = err
- return statement
- }
- tbs := strings.Split(tp.TableName(), ".")
- var aliasName = strings.Trim(tbs[len(tbs)-1], statement.Engine.QuoteStr())
- fmt.Fprintf(&buf, "(%s) %s ON %v", subSQL, aliasName, condition)
- statement.joinArgs = append(statement.joinArgs, subQueryArgs...)
- case *builder.Builder:
- subSQL, subQueryArgs, err := tp.ToSQL()
- if err != nil {
- statement.lastError = err
- return statement
- }
- tbs := strings.Split(tp.TableName(), ".")
- var aliasName = strings.Trim(tbs[len(tbs)-1], statement.Engine.QuoteStr())
- fmt.Fprintf(&buf, "(%s) %s ON %v", subSQL, aliasName, condition)
- statement.joinArgs = append(statement.joinArgs, subQueryArgs...)
- default:
- tbName := statement.Engine.TableName(tablename, true)
- fmt.Fprintf(&buf, "%s ON %v", tbName, condition)
- }
-
- statement.JoinStr = buf.String()
- statement.joinArgs = append(statement.joinArgs, args...)
- return statement
-}
-
-// GroupBy generate "Group By keys" statement
-func (statement *Statement) GroupBy(keys string) *Statement {
- statement.GroupByStr = keys
- return statement
-}
-
-// Having generate "Having conditions" statement
-func (statement *Statement) Having(conditions string) *Statement {
- statement.HavingStr = fmt.Sprintf("HAVING %v", conditions)
- return statement
-}
-
-// Unscoped always disable struct tag "deleted"
-func (statement *Statement) Unscoped() *Statement {
- statement.unscoped = true
- return statement
-}
-
-func (statement *Statement) genColumnStr() string {
- if statement.RefTable == nil {
- return ""
- }
-
- var buf builder.StringBuilder
- columns := statement.RefTable.Columns()
-
- for _, col := range columns {
- if statement.omitColumnMap.contain(col.Name) {
- continue
- }
-
- if len(statement.columnMap) > 0 && !statement.columnMap.contain(col.Name) {
- continue
- }
-
- if col.MapType == core.ONLYTODB {
- continue
- }
-
- if buf.Len() != 0 {
- buf.WriteString(", ")
- }
-
- if statement.JoinStr != "" {
- if statement.TableAlias != "" {
- buf.WriteString(statement.TableAlias)
- } else {
- buf.WriteString(statement.TableName())
- }
-
- buf.WriteString(".")
- }
-
- statement.Engine.QuoteTo(&buf, col.Name)
- }
-
- return buf.String()
-}
-
-func (statement *Statement) genCreateTableSQL() string {
- return statement.Engine.dialect.CreateTableSql(statement.RefTable, statement.TableName(),
- statement.StoreEngine, statement.Charset)
-}
-
-func (statement *Statement) genIndexSQL() []string {
- var sqls []string
- tbName := statement.TableName()
- for _, index := range statement.RefTable.Indexes {
- if index.Type == core.IndexType {
- sql := statement.Engine.dialect.CreateIndexSql(tbName, index)
- /*idxTBName := strings.Replace(tbName, ".", "_", -1)
- idxTBName = strings.Replace(idxTBName, `"`, "", -1)
- sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(idxTBName, idxName)),
- quote(tbName), quote(strings.Join(index.Cols, quote(","))))*/
- sqls = append(sqls, sql)
- }
- }
- return sqls
-}
-
-func uniqueName(tableName, uqeName string) string {
- return fmt.Sprintf("UQE_%v_%v", tableName, uqeName)
-}
-
-func (statement *Statement) genUniqueSQL() []string {
- var sqls []string
- tbName := statement.TableName()
- for _, index := range statement.RefTable.Indexes {
- if index.Type == core.UniqueType {
- sql := statement.Engine.dialect.CreateIndexSql(tbName, index)
- sqls = append(sqls, sql)
- }
- }
- return sqls
-}
-
-func (statement *Statement) genDelIndexSQL() []string {
- var sqls []string
- tbName := statement.TableName()
- idxPrefixName := strings.Replace(tbName, `"`, "", -1)
- idxPrefixName = strings.Replace(idxPrefixName, `.`, "_", -1)
- for idxName, index := range statement.RefTable.Indexes {
- var rIdxName string
- if index.Type == core.UniqueType {
- rIdxName = uniqueName(idxPrefixName, idxName)
- } else if index.Type == core.IndexType {
- rIdxName = indexName(idxPrefixName, idxName)
- }
- sql := fmt.Sprintf("DROP INDEX %v", statement.Engine.Quote(statement.Engine.TableName(rIdxName, true)))
- if statement.Engine.dialect.IndexOnTable() {
- sql += fmt.Sprintf(" ON %v", statement.Engine.Quote(tbName))
- }
- sqls = append(sqls, sql)
- }
- return sqls
-}
-
-func (statement *Statement) genAddColumnStr(col *core.Column) (string, []interface{}) {
- quote := statement.Engine.Quote
- sql := fmt.Sprintf("ALTER TABLE %v ADD %v", quote(statement.TableName()),
- col.String(statement.Engine.dialect))
- if statement.Engine.dialect.DBType() == core.MYSQL && len(col.Comment) > 0 {
- sql += " COMMENT '" + col.Comment + "'"
- }
- sql += ";"
- return sql, []interface{}{}
-}
-
-func (statement *Statement) buildConds(table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, addedTableName bool) (builder.Cond, error) {
- return statement.Engine.buildConds(table, bean, includeVersion, includeUpdated, includeNil, includeAutoIncr, statement.allUseBool, statement.useAllCols,
- statement.unscoped, statement.mustColumnMap, statement.TableName(), statement.TableAlias, addedTableName)
-}
-
-func (statement *Statement) mergeConds(bean interface{}) error {
- if !statement.noAutoCondition {
- var addedTableName = (len(statement.JoinStr) > 0)
- autoCond, err := statement.buildConds(statement.RefTable, bean, true, true, false, true, addedTableName)
- if err != nil {
- return err
- }
- statement.cond = statement.cond.And(autoCond)
- }
-
- if err := statement.processIDParam(); err != nil {
- return err
- }
- return nil
-}
-
-func (statement *Statement) genConds(bean interface{}) (string, []interface{}, error) {
- if err := statement.mergeConds(bean); err != nil {
- return "", nil, err
- }
-
- return builder.ToSQL(statement.cond)
-}
-
-func (statement *Statement) genGetSQL(bean interface{}) (string, []interface{}, error) {
- v := rValue(bean)
- isStruct := v.Kind() == reflect.Struct
- if isStruct {
- statement.setRefBean(bean)
- }
-
- var columnStr = statement.ColumnStr
- if len(statement.selectStr) > 0 {
- columnStr = statement.selectStr
- } else {
- // TODO: always generate column names, not use * even if join
- if len(statement.JoinStr) == 0 {
- if len(columnStr) == 0 {
- if len(statement.GroupByStr) > 0 {
- columnStr = statement.Engine.quoteColumns(statement.GroupByStr)
- } else {
- columnStr = statement.genColumnStr()
- }
- }
- } else {
- if len(columnStr) == 0 {
- if len(statement.GroupByStr) > 0 {
- columnStr = statement.Engine.quoteColumns(statement.GroupByStr)
- }
- }
- }
- }
-
- if len(columnStr) == 0 {
- columnStr = "*"
- }
-
- if isStruct {
- if err := statement.mergeConds(bean); err != nil {
- return "", nil, err
- }
- } else {
- if err := statement.processIDParam(); err != nil {
- return "", nil, err
- }
- }
- condSQL, condArgs, err := builder.ToSQL(statement.cond)
- if err != nil {
- return "", nil, err
- }
-
- sqlStr, err := statement.genSelectSQL(columnStr, condSQL, true, true)
- if err != nil {
- return "", nil, err
- }
-
- return sqlStr, append(statement.joinArgs, condArgs...), nil
-}
-
-func (statement *Statement) genCountSQL(beans ...interface{}) (string, []interface{}, error) {
- var condSQL string
- var condArgs []interface{}
- var err error
- if len(beans) > 0 {
- statement.setRefBean(beans[0])
- condSQL, condArgs, err = statement.genConds(beans[0])
- } else {
- condSQL, condArgs, err = builder.ToSQL(statement.cond)
- }
- if err != nil {
- return "", nil, err
- }
-
- var selectSQL = statement.selectStr
- if len(selectSQL) <= 0 {
- if statement.IsDistinct {
- selectSQL = fmt.Sprintf("count(DISTINCT %s)", statement.ColumnStr)
- } else {
- selectSQL = "count(*)"
- }
- }
- sqlStr, err := statement.genSelectSQL(selectSQL, condSQL, false, false)
- if err != nil {
- return "", nil, err
- }
-
- return sqlStr, append(statement.joinArgs, condArgs...), nil
-}
-
-func (statement *Statement) genSumSQL(bean interface{}, columns ...string) (string, []interface{}, error) {
- statement.setRefBean(bean)
-
- var sumStrs = make([]string, 0, len(columns))
- for _, colName := range columns {
- if !strings.Contains(colName, " ") && !strings.Contains(colName, "(") {
- colName = statement.Engine.Quote(colName)
- }
- sumStrs = append(sumStrs, fmt.Sprintf("COALESCE(sum(%s),0)", colName))
- }
- sumSelect := strings.Join(sumStrs, ", ")
-
- condSQL, condArgs, err := statement.genConds(bean)
- if err != nil {
- return "", nil, err
- }
-
- sqlStr, err := statement.genSelectSQL(sumSelect, condSQL, true, true)
- if err != nil {
- return "", nil, err
- }
-
- return sqlStr, append(statement.joinArgs, condArgs...), nil
-}
-
-func (statement *Statement) genSelectSQL(columnStr, condSQL string, needLimit, needOrderBy bool) (string, error) {
- var (
- distinct string
- dialect = statement.Engine.Dialect()
- quote = statement.Engine.Quote
- fromStr = " FROM "
- top, mssqlCondi, whereStr string
- )
- if statement.IsDistinct && !strings.HasPrefix(columnStr, "count") {
- distinct = "DISTINCT "
- }
- if len(condSQL) > 0 {
- whereStr = " WHERE " + condSQL
- }
-
- if dialect.DBType() == core.MSSQL && strings.Contains(statement.TableName(), "..") {
- fromStr += statement.TableName()
- } else {
- fromStr += quote(statement.TableName())
- }
-
- if statement.TableAlias != "" {
- if dialect.DBType() == core.ORACLE {
- fromStr += " " + quote(statement.TableAlias)
- } else {
- fromStr += " AS " + quote(statement.TableAlias)
- }
- }
- if statement.JoinStr != "" {
- fromStr = fmt.Sprintf("%v %v", fromStr, statement.JoinStr)
- }
-
- if dialect.DBType() == core.MSSQL {
- if statement.LimitN > 0 {
- top = fmt.Sprintf("TOP %d ", statement.LimitN)
- }
- if statement.Start > 0 {
- var column string
- if len(statement.RefTable.PKColumns()) == 0 {
- for _, index := range statement.RefTable.Indexes {
- if len(index.Cols) == 1 {
- column = index.Cols[0]
- break
- }
- }
- if len(column) == 0 {
- column = statement.RefTable.ColumnsSeq()[0]
- }
- } else {
- column = statement.RefTable.PKColumns()[0].Name
- }
- if statement.needTableName() {
- if len(statement.TableAlias) > 0 {
- column = statement.TableAlias + "." + column
- } else {
- column = statement.TableName() + "." + column
- }
- }
-
- var orderStr string
- if needOrderBy && len(statement.OrderStr) > 0 {
- orderStr = " ORDER BY " + statement.OrderStr
- }
-
- var groupStr string
- if len(statement.GroupByStr) > 0 {
- groupStr = " GROUP BY " + statement.GroupByStr
- }
- mssqlCondi = fmt.Sprintf("(%s NOT IN (SELECT TOP %d %s%s%s%s%s))",
- column, statement.Start, column, fromStr, whereStr, orderStr, groupStr)
- }
- }
-
- var buf builder.StringBuilder
- fmt.Fprintf(&buf, "SELECT %v%v%v%v%v", distinct, top, columnStr, fromStr, whereStr)
- if len(mssqlCondi) > 0 {
- if len(whereStr) > 0 {
- fmt.Fprint(&buf, " AND ", mssqlCondi)
- } else {
- fmt.Fprint(&buf, " WHERE ", mssqlCondi)
- }
- }
-
- if statement.GroupByStr != "" {
- fmt.Fprint(&buf, " GROUP BY ", statement.GroupByStr)
- }
- if statement.HavingStr != "" {
- fmt.Fprint(&buf, " ", statement.HavingStr)
- }
- if needOrderBy && statement.OrderStr != "" {
- fmt.Fprint(&buf, " ORDER BY ", statement.OrderStr)
- }
- if needLimit {
- if dialect.DBType() != core.MSSQL && dialect.DBType() != core.ORACLE {
- if statement.Start > 0 {
- fmt.Fprintf(&buf, " LIMIT %v OFFSET %v", statement.LimitN, statement.Start)
- } else if statement.LimitN > 0 {
- fmt.Fprint(&buf, " LIMIT ", statement.LimitN)
- }
- } else if dialect.DBType() == core.ORACLE {
- if statement.Start != 0 || statement.LimitN != 0 {
- oldString := buf.String()
- buf.Reset()
- fmt.Fprintf(&buf, "SELECT %v FROM (SELECT %v,ROWNUM RN FROM (%v) at WHERE ROWNUM <= %d) aat WHERE RN > %d",
- columnStr, columnStr, oldString, statement.Start+statement.LimitN, statement.Start)
- }
- }
- }
- if statement.IsForUpdate {
- return dialect.ForUpdateSql(buf.String()), nil
- }
-
- return buf.String(), nil
-}
-
-func (statement *Statement) processIDParam() error {
- if statement.idParam == nil || statement.RefTable == nil {
- return nil
- }
-
- if len(statement.RefTable.PrimaryKeys) != len(*statement.idParam) {
- return fmt.Errorf("ID condition is error, expect %d primarykeys, there are %d",
- len(statement.RefTable.PrimaryKeys),
- len(*statement.idParam),
- )
- }
-
- for i, col := range statement.RefTable.PKColumns() {
- var colName = statement.colName(col, statement.TableName())
- statement.cond = statement.cond.And(builder.Eq{colName: (*(statement.idParam))[i]})
- }
- return nil
-}
-
-func (statement *Statement) joinColumns(cols []*core.Column, includeTableName bool) string {
- var colnames = make([]string, len(cols))
- for i, col := range cols {
- if includeTableName {
- colnames[i] = statement.Engine.Quote(statement.TableName()) +
- "." + statement.Engine.Quote(col.Name)
- } else {
- colnames[i] = statement.Engine.Quote(col.Name)
- }
- }
- return strings.Join(colnames, ", ")
-}
-
-func (statement *Statement) convertIDSQL(sqlStr string) string {
- if statement.RefTable != nil {
- cols := statement.RefTable.PKColumns()
- if len(cols) == 0 {
- return ""
- }
-
- colstrs := statement.joinColumns(cols, false)
- sqls := splitNNoCase(sqlStr, " from ", 2)
- if len(sqls) != 2 {
- return ""
- }
-
- var top string
- if statement.LimitN > 0 && statement.Engine.dialect.DBType() == core.MSSQL {
- top = fmt.Sprintf("TOP %d ", statement.LimitN)
- }
-
- newsql := fmt.Sprintf("SELECT %s%s FROM %v", top, colstrs, sqls[1])
- return newsql
- }
- return ""
-}
-
-func (statement *Statement) convertUpdateSQL(sqlStr string) (string, string) {
- if statement.RefTable == nil || len(statement.RefTable.PrimaryKeys) != 1 {
- return "", ""
- }
-
- colstrs := statement.joinColumns(statement.RefTable.PKColumns(), true)
- sqls := splitNNoCase(sqlStr, "where", 2)
- if len(sqls) != 2 {
- if len(sqls) == 1 {
- return sqls[0], fmt.Sprintf("SELECT %v FROM %v",
- colstrs, statement.Engine.Quote(statement.TableName()))
- }
- return "", ""
- }
-
- var whereStr = sqls[1]
-
- //TODO: for postgres only, if any other database?
- var paraStr string
- if statement.Engine.dialect.DBType() == core.POSTGRES {
- paraStr = "$"
- } else if statement.Engine.dialect.DBType() == core.MSSQL {
- paraStr = ":"
- }
-
- if paraStr != "" {
- if strings.Contains(sqls[1], paraStr) {
- dollers := strings.Split(sqls[1], paraStr)
- whereStr = dollers[0]
- for i, c := range dollers[1:] {
- ccs := strings.SplitN(c, " ", 2)
- whereStr += fmt.Sprintf(paraStr+"%v %v", i+1, ccs[1])
- }
- }
- }
-
- return sqls[0], fmt.Sprintf("SELECT %v FROM %v WHERE %v",
- colstrs, statement.Engine.Quote(statement.TableName()),
- whereStr)
-}
diff --git a/vendor/github.com/go-xorm/xorm/syslogger.go b/vendor/github.com/go-xorm/xorm/syslogger.go
deleted file mode 100644
index 11ba01e..0000000
--- a/vendor/github.com/go-xorm/xorm/syslogger.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !windows,!nacl,!plan9
-
-package xorm
-
-import (
- "fmt"
- "log/syslog"
-
- "xorm.io/core"
-)
-
-var _ core.ILogger = &SyslogLogger{}
-
-// SyslogLogger will be depricated
-type SyslogLogger struct {
- w *syslog.Writer
- showSQL bool
-}
-
-// NewSyslogLogger implements core.ILogger
-func NewSyslogLogger(w *syslog.Writer) *SyslogLogger {
- return &SyslogLogger{w: w}
-}
-
-// Debug log content as Debug
-func (s *SyslogLogger) Debug(v ...interface{}) {
- s.w.Debug(fmt.Sprint(v...))
-}
-
-// Debugf log content as Debug and format
-func (s *SyslogLogger) Debugf(format string, v ...interface{}) {
- s.w.Debug(fmt.Sprintf(format, v...))
-}
-
-// Error log content as Error
-func (s *SyslogLogger) Error(v ...interface{}) {
- s.w.Err(fmt.Sprint(v...))
-}
-
-// Errorf log content as Errorf and format
-func (s *SyslogLogger) Errorf(format string, v ...interface{}) {
- s.w.Err(fmt.Sprintf(format, v...))
-}
-
-// Info log content as Info
-func (s *SyslogLogger) Info(v ...interface{}) {
- s.w.Info(fmt.Sprint(v...))
-}
-
-// Infof log content as Infof and format
-func (s *SyslogLogger) Infof(format string, v ...interface{}) {
- s.w.Info(fmt.Sprintf(format, v...))
-}
-
-// Warn log content as Warn
-func (s *SyslogLogger) Warn(v ...interface{}) {
- s.w.Warning(fmt.Sprint(v...))
-}
-
-// Warnf log content as Warnf and format
-func (s *SyslogLogger) Warnf(format string, v ...interface{}) {
- s.w.Warning(fmt.Sprintf(format, v...))
-}
-
-// Level shows log level
-func (s *SyslogLogger) Level() core.LogLevel {
- return core.LOG_UNKNOWN
-}
-
-// SetLevel always return error, as current log/syslog package doesn't allow to set priority level after syslog.Writer created
-func (s *SyslogLogger) SetLevel(l core.LogLevel) {}
-
-// ShowSQL set if logging SQL
-func (s *SyslogLogger) ShowSQL(show ...bool) {
- if len(show) == 0 {
- s.showSQL = true
- return
- }
- s.showSQL = show[0]
-}
-
-// IsShowSQL if logging SQL
-func (s *SyslogLogger) IsShowSQL() bool {
- return s.showSQL
-}
diff --git a/vendor/github.com/go-xorm/xorm/tag.go b/vendor/github.com/go-xorm/xorm/tag.go
deleted file mode 100644
index 6feb581..0000000
--- a/vendor/github.com/go-xorm/xorm/tag.go
+++ /dev/null
@@ -1,310 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "time"
-
- "xorm.io/core"
-)
-
-type tagContext struct {
- tagName string
- params []string
- preTag, nextTag string
- table *core.Table
- col *core.Column
- fieldValue reflect.Value
- isIndex bool
- isUnique bool
- indexNames map[string]int
- engine *Engine
- hasCacheTag bool
- hasNoCacheTag bool
- ignoreNext bool
-}
-
-// tagHandler describes tag handler for XORM
-type tagHandler func(ctx *tagContext) error
-
-var (
- // defaultTagHandlers enumerates all the default tag handler
- defaultTagHandlers = map[string]tagHandler{
- "<-": OnlyFromDBTagHandler,
- "->": OnlyToDBTagHandler,
- "PK": PKTagHandler,
- "NULL": NULLTagHandler,
- "NOT": IgnoreTagHandler,
- "AUTOINCR": AutoIncrTagHandler,
- "DEFAULT": DefaultTagHandler,
- "CREATED": CreatedTagHandler,
- "UPDATED": UpdatedTagHandler,
- "DELETED": DeletedTagHandler,
- "VERSION": VersionTagHandler,
- "UTC": UTCTagHandler,
- "LOCAL": LocalTagHandler,
- "NOTNULL": NotNullTagHandler,
- "INDEX": IndexTagHandler,
- "UNIQUE": UniqueTagHandler,
- "CACHE": CacheTagHandler,
- "NOCACHE": NoCacheTagHandler,
- "COMMENT": CommentTagHandler,
- }
-)
-
-func init() {
- for k := range core.SqlTypes {
- defaultTagHandlers[k] = SQLTypeTagHandler
- }
-}
-
-// IgnoreTagHandler describes ignored tag handler
-func IgnoreTagHandler(ctx *tagContext) error {
- return nil
-}
-
-// OnlyFromDBTagHandler describes mapping direction tag handler
-func OnlyFromDBTagHandler(ctx *tagContext) error {
- ctx.col.MapType = core.ONLYFROMDB
- return nil
-}
-
-// OnlyToDBTagHandler describes mapping direction tag handler
-func OnlyToDBTagHandler(ctx *tagContext) error {
- ctx.col.MapType = core.ONLYTODB
- return nil
-}
-
-// PKTagHandler decribes primary key tag handler
-func PKTagHandler(ctx *tagContext) error {
- ctx.col.IsPrimaryKey = true
- ctx.col.Nullable = false
- return nil
-}
-
-// NULLTagHandler describes null tag handler
-func NULLTagHandler(ctx *tagContext) error {
- ctx.col.Nullable = (strings.ToUpper(ctx.preTag) != "NOT")
- return nil
-}
-
-// NotNullTagHandler describes notnull tag handler
-func NotNullTagHandler(ctx *tagContext) error {
- ctx.col.Nullable = false
- return nil
-}
-
-// AutoIncrTagHandler describes autoincr tag handler
-func AutoIncrTagHandler(ctx *tagContext) error {
- ctx.col.IsAutoIncrement = true
- /*
- if len(ctx.params) > 0 {
- autoStartInt, err := strconv.Atoi(ctx.params[0])
- if err != nil {
- return err
- }
- ctx.col.AutoIncrStart = autoStartInt
- } else {
- ctx.col.AutoIncrStart = 1
- }
- */
- return nil
-}
-
-// DefaultTagHandler describes default tag handler
-func DefaultTagHandler(ctx *tagContext) error {
- if len(ctx.params) > 0 {
- ctx.col.Default = ctx.params[0]
- } else {
- ctx.col.Default = ctx.nextTag
- ctx.ignoreNext = true
- }
- return nil
-}
-
-// CreatedTagHandler describes created tag handler
-func CreatedTagHandler(ctx *tagContext) error {
- ctx.col.IsCreated = true
- return nil
-}
-
-// VersionTagHandler describes version tag handler
-func VersionTagHandler(ctx *tagContext) error {
- ctx.col.IsVersion = true
- ctx.col.Default = "1"
- return nil
-}
-
-// UTCTagHandler describes utc tag handler
-func UTCTagHandler(ctx *tagContext) error {
- ctx.col.TimeZone = time.UTC
- return nil
-}
-
-// LocalTagHandler describes local tag handler
-func LocalTagHandler(ctx *tagContext) error {
- if len(ctx.params) == 0 {
- ctx.col.TimeZone = time.Local
- } else {
- var err error
- ctx.col.TimeZone, err = time.LoadLocation(ctx.params[0])
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// UpdatedTagHandler describes updated tag handler
-func UpdatedTagHandler(ctx *tagContext) error {
- ctx.col.IsUpdated = true
- return nil
-}
-
-// DeletedTagHandler describes deleted tag handler
-func DeletedTagHandler(ctx *tagContext) error {
- ctx.col.IsDeleted = true
- return nil
-}
-
-// IndexTagHandler describes index tag handler
-func IndexTagHandler(ctx *tagContext) error {
- if len(ctx.params) > 0 {
- ctx.indexNames[ctx.params[0]] = core.IndexType
- } else {
- ctx.isIndex = true
- }
- return nil
-}
-
-// UniqueTagHandler describes unique tag handler
-func UniqueTagHandler(ctx *tagContext) error {
- if len(ctx.params) > 0 {
- ctx.indexNames[ctx.params[0]] = core.UniqueType
- } else {
- ctx.isUnique = true
- }
- return nil
-}
-
-// CommentTagHandler add comment to column
-func CommentTagHandler(ctx *tagContext) error {
- if len(ctx.params) > 0 {
- ctx.col.Comment = strings.Trim(ctx.params[0], "' ")
- }
- return nil
-}
-
-// SQLTypeTagHandler describes SQL Type tag handler
-func SQLTypeTagHandler(ctx *tagContext) error {
- ctx.col.SQLType = core.SQLType{Name: ctx.tagName}
- if len(ctx.params) > 0 {
- if ctx.tagName == core.Enum {
- ctx.col.EnumOptions = make(map[string]int)
- for k, v := range ctx.params {
- v = strings.TrimSpace(v)
- v = strings.Trim(v, "'")
- ctx.col.EnumOptions[v] = k
- }
- } else if ctx.tagName == core.Set {
- ctx.col.SetOptions = make(map[string]int)
- for k, v := range ctx.params {
- v = strings.TrimSpace(v)
- v = strings.Trim(v, "'")
- ctx.col.SetOptions[v] = k
- }
- } else {
- var err error
- if len(ctx.params) == 2 {
- ctx.col.Length, err = strconv.Atoi(ctx.params[0])
- if err != nil {
- return err
- }
- ctx.col.Length2, err = strconv.Atoi(ctx.params[1])
- if err != nil {
- return err
- }
- } else if len(ctx.params) == 1 {
- ctx.col.Length, err = strconv.Atoi(ctx.params[0])
- if err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-// ExtendsTagHandler describes extends tag handler
-func ExtendsTagHandler(ctx *tagContext) error {
- var fieldValue = ctx.fieldValue
- var isPtr = false
- switch fieldValue.Kind() {
- case reflect.Ptr:
- f := fieldValue.Type().Elem()
- if f.Kind() == reflect.Struct {
- fieldPtr := fieldValue
- fieldValue = fieldValue.Elem()
- if !fieldValue.IsValid() || fieldPtr.IsNil() {
- fieldValue = reflect.New(f).Elem()
- }
- }
- isPtr = true
- fallthrough
- case reflect.Struct:
- parentTable, err := ctx.engine.mapType(fieldValue)
- if err != nil {
- return err
- }
- for _, col := range parentTable.Columns() {
- col.FieldName = fmt.Sprintf("%v.%v", ctx.col.FieldName, col.FieldName)
-
- var tagPrefix = ctx.col.FieldName
- if len(ctx.params) > 0 {
- col.Nullable = isPtr
- tagPrefix = ctx.params[0]
- if col.IsPrimaryKey {
- col.Name = ctx.col.FieldName
- col.IsPrimaryKey = false
- } else {
- col.Name = fmt.Sprintf("%v%v", tagPrefix, col.Name)
- }
- }
-
- if col.Nullable {
- col.IsAutoIncrement = false
- col.IsPrimaryKey = false
- }
-
- ctx.table.AddColumn(col)
- for indexName, indexType := range col.Indexes {
- addIndex(indexName, ctx.table, col, indexType)
- }
- }
- default:
- //TODO: warning
- }
- return nil
-}
-
-// CacheTagHandler describes cache tag handler
-func CacheTagHandler(ctx *tagContext) error {
- if !ctx.hasCacheTag {
- ctx.hasCacheTag = true
- }
- return nil
-}
-
-// NoCacheTagHandler describes nocache tag handler
-func NoCacheTagHandler(ctx *tagContext) error {
- if !ctx.hasNoCacheTag {
- ctx.hasNoCacheTag = true
- }
- return nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/test_mssql.sh b/vendor/github.com/go-xorm/xorm/test_mssql.sh
deleted file mode 100644
index 7f060cf..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mssql.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mssql -conn_str="server=localhost;user id=sa;password=yourStrong(!)Password;database=xorm_test"
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_mssql_cache.sh b/vendor/github.com/go-xorm/xorm/test_mssql_cache.sh
deleted file mode 100644
index 76efd6c..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mssql_cache.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mssql -conn_str="server=192.168.1.58;user id=sa;password=123456;database=xorm_test" -cache=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_mymysql.sh b/vendor/github.com/go-xorm/xorm/test_mymysql.sh
deleted file mode 100644
index f7780d1..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mymysql.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mymysql -conn_str="xorm_test/root/"
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_mymysql_cache.sh b/vendor/github.com/go-xorm/xorm/test_mymysql_cache.sh
deleted file mode 100644
index 0100286..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mymysql_cache.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mymysql -conn_str="xorm_test/root/" -cache=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_mysql.sh b/vendor/github.com/go-xorm/xorm/test_mysql.sh
deleted file mode 100644
index 650e4ee..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mysql.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mysql -conn_str="root:@/xorm_test"
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_mysql_cache.sh b/vendor/github.com/go-xorm/xorm/test_mysql_cache.sh
deleted file mode 100644
index c542e73..0000000
--- a/vendor/github.com/go-xorm/xorm/test_mysql_cache.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mysql -conn_str="root:@/xorm_test" -cache=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_postgres.sh b/vendor/github.com/go-xorm/xorm/test_postgres.sh
deleted file mode 100644
index dc1152e..0000000
--- a/vendor/github.com/go-xorm/xorm/test_postgres.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=postgres -conn_str="dbname=xorm_test sslmode=disable"
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_postgres_cache.sh b/vendor/github.com/go-xorm/xorm/test_postgres_cache.sh
deleted file mode 100644
index 462fc94..0000000
--- a/vendor/github.com/go-xorm/xorm/test_postgres_cache.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=postgres -conn_str="dbname=xorm_test sslmode=disable" -cache=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_sqlite.sh b/vendor/github.com/go-xorm/xorm/test_sqlite.sh
deleted file mode 100644
index 6352b5c..0000000
--- a/vendor/github.com/go-xorm/xorm/test_sqlite.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=sqlite3 -conn_str="./test.db?cache=shared&mode=rwc"
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_sqlite_cache.sh b/vendor/github.com/go-xorm/xorm/test_sqlite_cache.sh
deleted file mode 100644
index 75a054c..0000000
--- a/vendor/github.com/go-xorm/xorm/test_sqlite_cache.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=sqlite3 -conn_str="./test.db?cache=shared&mode=rwc" -cache=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/test_tidb.sh b/vendor/github.com/go-xorm/xorm/test_tidb.sh
deleted file mode 100644
index 03d2d6c..0000000
--- a/vendor/github.com/go-xorm/xorm/test_tidb.sh
+++ /dev/null
@@ -1 +0,0 @@
-go test -db=mysql -conn_str="root:@tcp(localhost:4000)/xorm_test" -ignore_select_update=true
\ No newline at end of file
diff --git a/vendor/github.com/go-xorm/xorm/transaction.go b/vendor/github.com/go-xorm/xorm/transaction.go
deleted file mode 100644
index 4104103..0000000
--- a/vendor/github.com/go-xorm/xorm/transaction.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2018 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-// Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
-func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
- session := engine.NewSession()
- defer session.Close()
-
- if err := session.Begin(); err != nil {
- return nil, err
- }
-
- result, err := f(session)
- if err != nil {
- return nil, err
- }
-
- if err := session.Commit(); err != nil {
- return nil, err
- }
-
- return result, nil
-}
diff --git a/vendor/github.com/go-xorm/xorm/types.go b/vendor/github.com/go-xorm/xorm/types.go
deleted file mode 100644
index c76a546..0000000
--- a/vendor/github.com/go-xorm/xorm/types.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2017 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package xorm
-
-import (
- "reflect"
-
- "xorm.io/core"
-)
-
-var (
- ptrPkType = reflect.TypeOf(&core.PK{})
- pkType = reflect.TypeOf(core.PK{})
-)
diff --git a/vendor/github.com/go-xorm/xorm/xorm.go b/vendor/github.com/go-xorm/xorm/xorm.go
deleted file mode 100644
index 26d00d2..0000000
--- a/vendor/github.com/go-xorm/xorm/xorm.go
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2015 The Xorm Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build go1.8
-
-package xorm
-
-import (
- "context"
- "fmt"
- "os"
- "reflect"
- "runtime"
- "sync"
- "time"
-
- "xorm.io/core"
-)
-
-const (
- // Version show the xorm's version
- Version string = "0.7.0.0504"
-)
-
-func regDrvsNDialects() bool {
- providedDrvsNDialects := map[string]struct {
- dbType core.DbType
- getDriver func() core.Driver
- getDialect func() core.Dialect
- }{
- "mssql": {"mssql", func() core.Driver { return &odbcDriver{} }, func() core.Dialect { return &mssql{} }},
- "odbc": {"mssql", func() core.Driver { return &odbcDriver{} }, func() core.Dialect { return &mssql{} }}, // !nashtsai! TODO change this when supporting MS Access
- "mysql": {"mysql", func() core.Driver { return &mysqlDriver{} }, func() core.Dialect { return &mysql{} }},
- "mymysql": {"mysql", func() core.Driver { return &mymysqlDriver{} }, func() core.Dialect { return &mysql{} }},
- "postgres": {"postgres", func() core.Driver { return &pqDriver{} }, func() core.Dialect { return &postgres{} }},
- "pgx": {"postgres", func() core.Driver { return &pqDriverPgx{} }, func() core.Dialect { return &postgres{} }},
- "sqlite3": {"sqlite3", func() core.Driver { return &sqlite3Driver{} }, func() core.Dialect { return &sqlite3{} }},
- "oci8": {"oracle", func() core.Driver { return &oci8Driver{} }, func() core.Dialect { return &oracle{} }},
- "goracle": {"oracle", func() core.Driver { return &goracleDriver{} }, func() core.Dialect { return &oracle{} }},
- }
-
- for driverName, v := range providedDrvsNDialects {
- if driver := core.QueryDriver(driverName); driver == nil {
- core.RegisterDriver(driverName, v.getDriver())
- core.RegisterDialect(v.dbType, v.getDialect)
- }
- }
- return true
-}
-
-func close(engine *Engine) {
- engine.Close()
-}
-
-func init() {
- regDrvsNDialects()
-}
-
-// NewEngine new a db manager according to the parameter. Currently support four
-// drivers
-func NewEngine(driverName string, dataSourceName string) (*Engine, error) {
- driver := core.QueryDriver(driverName)
- if driver == nil {
- return nil, fmt.Errorf("Unsupported driver name: %v", driverName)
- }
-
- uri, err := driver.Parse(driverName, dataSourceName)
- if err != nil {
- return nil, err
- }
-
- dialect := core.QueryDialect(uri.DbType)
- if dialect == nil {
- return nil, fmt.Errorf("Unsupported dialect type: %v", uri.DbType)
- }
-
- db, err := core.Open(driverName, dataSourceName)
- if err != nil {
- return nil, err
- }
-
- err = dialect.Init(db, uri, driverName, dataSourceName)
- if err != nil {
- return nil, err
- }
-
- engine := &Engine{
- db: db,
- dialect: dialect,
- Tables: make(map[reflect.Type]*core.Table),
- mutex: &sync.RWMutex{},
- TagIdentifier: "xorm",
- TZLocation: time.Local,
- tagHandlers: defaultTagHandlers,
- cachers: make(map[string]core.Cacher),
- defaultContext: context.Background(),
- }
-
- if uri.DbType == core.SQLITE {
- engine.DatabaseTZ = time.UTC
- } else {
- engine.DatabaseTZ = time.Local
- }
-
- logger := NewSimpleLogger(os.Stdout)
- logger.SetLevel(core.LOG_INFO)
- engine.SetLogger(logger)
- engine.SetMapper(core.NewCacheMapper(new(core.SnakeMapper)))
-
- runtime.SetFinalizer(engine, close)
-
- return engine, nil
-}
-
-// NewEngineWithParams new a db manager with params. The params will be passed to dialect.
-func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error) {
- engine, err := NewEngine(driverName, dataSourceName)
- engine.dialect.SetParams(params)
- return engine, err
-}
-
-// Clone clone an engine
-func (engine *Engine) Clone() (*Engine, error) {
- return NewEngine(engine.DriverName(), engine.DataSourceName())
-}
diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS
deleted file mode 100644
index 15167cd..0000000
--- a/vendor/github.com/golang/protobuf/AUTHORS
+++ /dev/null
@@ -1,3 +0,0 @@
-# This source code refers to The Go Authors for copyright purposes.
-# The master list of authors is in the main Go distribution,
-# visible at http://tip.golang.org/AUTHORS.
diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS
deleted file mode 100644
index 1c4577e..0000000
--- a/vendor/github.com/golang/protobuf/CONTRIBUTORS
+++ /dev/null
@@ -1,3 +0,0 @@
-# This source code was written by the Go contributors.
-# The master list of contributors is in the main Go distribution,
-# visible at http://tip.golang.org/CONTRIBUTORS.
diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE
deleted file mode 100644
index 0f64693..0000000
--- a/vendor/github.com/golang/protobuf/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2010 The Go Authors. 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"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 THE COPYRIGHT
-OWNER OR CONTRIBUTORS 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.
-
diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go
deleted file mode 100644
index 3cd3249..0000000
--- a/vendor/github.com/golang/protobuf/proto/clone.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-// Protocol buffer deep copy and merge.
-// TODO: RawMessage.
-
-package proto
-
-import (
- "fmt"
- "log"
- "reflect"
- "strings"
-)
-
-// Clone returns a deep copy of a protocol buffer.
-func Clone(src Message) Message {
- in := reflect.ValueOf(src)
- if in.IsNil() {
- return src
- }
- out := reflect.New(in.Type().Elem())
- dst := out.Interface().(Message)
- Merge(dst, src)
- return dst
-}
-
-// Merger is the interface representing objects that can merge messages of the same type.
-type Merger interface {
- // Merge merges src into this message.
- // Required and optional fields that are set in src will be set to that value in dst.
- // Elements of repeated fields will be appended.
- //
- // Merge may panic if called with a different argument type than the receiver.
- Merge(src Message)
-}
-
-// generatedMerger is the custom merge method that generated protos will have.
-// We must add this method since a generate Merge method will conflict with
-// many existing protos that have a Merge data field already defined.
-type generatedMerger interface {
- XXX_Merge(src Message)
-}
-
-// Merge merges src into dst.
-// Required and optional fields that are set in src will be set to that value in dst.
-// Elements of repeated fields will be appended.
-// Merge panics if src and dst are not the same type, or if dst is nil.
-func Merge(dst, src Message) {
- if m, ok := dst.(Merger); ok {
- m.Merge(src)
- return
- }
-
- in := reflect.ValueOf(src)
- out := reflect.ValueOf(dst)
- if out.IsNil() {
- panic("proto: nil destination")
- }
- if in.Type() != out.Type() {
- panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
- }
- if in.IsNil() {
- return // Merge from nil src is a noop
- }
- if m, ok := dst.(generatedMerger); ok {
- m.XXX_Merge(src)
- return
- }
- mergeStruct(out.Elem(), in.Elem())
-}
-
-func mergeStruct(out, in reflect.Value) {
- sprop := GetProperties(in.Type())
- for i := 0; i < in.NumField(); i++ {
- f := in.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
- }
-
- if emIn, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- uf := in.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return
- }
- uin := uf.Bytes()
- if len(uin) > 0 {
- out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
- }
-}
-
-// mergeAny performs a merge between two values of the same type.
-// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
-// prop is set if this is a struct field (it may be nil).
-func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
- if in.Type() == protoMessageType {
- if !in.IsNil() {
- if out.IsNil() {
- out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
- } else {
- Merge(out.Interface().(Message), in.Interface().(Message))
- }
- }
- return
- }
- switch in.Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- if !viaPtr && isProto3Zero(in) {
- return
- }
- out.Set(in)
- case reflect.Interface:
- // Probably a oneof field; copy non-nil values.
- if in.IsNil() {
- return
- }
- // Allocate destination if it is not set, or set to a different type.
- // Otherwise we will merge as normal.
- if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
- out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
- }
- mergeAny(out.Elem(), in.Elem(), false, nil)
- case reflect.Map:
- if in.Len() == 0 {
- return
- }
- if out.IsNil() {
- out.Set(reflect.MakeMap(in.Type()))
- }
- // For maps with value types of *T or []byte we need to deep copy each value.
- elemKind := in.Type().Elem().Kind()
- for _, key := range in.MapKeys() {
- var val reflect.Value
- switch elemKind {
- case reflect.Ptr:
- val = reflect.New(in.Type().Elem().Elem())
- mergeAny(val, in.MapIndex(key), false, nil)
- case reflect.Slice:
- val = in.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- default:
- val = in.MapIndex(key)
- }
- out.SetMapIndex(key, val)
- }
- case reflect.Ptr:
- if in.IsNil() {
- return
- }
- if out.IsNil() {
- out.Set(reflect.New(in.Elem().Type()))
- }
- mergeAny(out.Elem(), in.Elem(), true, nil)
- case reflect.Slice:
- if in.IsNil() {
- return
- }
- if in.Type().Elem().Kind() == reflect.Uint8 {
- // []byte is a scalar bytes field, not a repeated field.
-
- // Edge case: if this is in a proto3 message, a zero length
- // bytes field is considered the zero value, and should not
- // be merged.
- if prop != nil && prop.proto3 && in.Len() == 0 {
- return
- }
-
- // Make a deep copy.
- // Append to []byte{} instead of []byte(nil) so that we never end up
- // with a nil result.
- out.SetBytes(append([]byte{}, in.Bytes()...))
- return
- }
- n := in.Len()
- if out.IsNil() {
- out.Set(reflect.MakeSlice(in.Type(), 0, n))
- }
- switch in.Type().Elem().Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- out.Set(reflect.AppendSlice(out, in))
- default:
- for i := 0; i < n; i++ {
- x := reflect.Indirect(reflect.New(in.Type().Elem()))
- mergeAny(x, in.Index(i), false, nil)
- out.Set(reflect.Append(out, x))
- }
- }
- case reflect.Struct:
- mergeStruct(out, in)
- default:
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to copy %v", in)
- }
-}
-
-func mergeExtension(out, in map[int32]Extension) {
- for extNum, eIn := range in {
- eOut := Extension{desc: eIn.desc}
- if eIn.value != nil {
- v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
- mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
- eOut.value = v.Interface()
- }
- if eIn.enc != nil {
- eOut.enc = make([]byte, len(eIn.enc))
- copy(eOut.enc, eIn.enc)
- }
-
- out[extNum] = eOut
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go
deleted file mode 100644
index 63b0f08..0000000
--- a/vendor/github.com/golang/protobuf/proto/decode.go
+++ /dev/null
@@ -1,427 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-/*
- * Routines for decoding protocol buffer data to construct in-memory representations.
- */
-
-import (
- "errors"
- "fmt"
- "io"
-)
-
-// errOverflow is returned when an integer is too large to be represented.
-var errOverflow = errors.New("proto: integer overflow")
-
-// ErrInternalBadWireType is returned by generated code when an incorrect
-// wire type is encountered. It does not get returned to user code.
-var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
-
-// DecodeVarint reads a varint-encoded integer from the slice.
-// It returns the integer and the number of bytes consumed, or
-// zero if there is not enough.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func DecodeVarint(buf []byte) (x uint64, n int) {
- for shift := uint(0); shift < 64; shift += 7 {
- if n >= len(buf) {
- return 0, 0
- }
- b := uint64(buf[n])
- n++
- x |= (b & 0x7F) << shift
- if (b & 0x80) == 0 {
- return x, n
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- return 0, 0
-}
-
-func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
- i := p.index
- l := len(p.buf)
-
- for shift := uint(0); shift < 64; shift += 7 {
- if i >= l {
- err = io.ErrUnexpectedEOF
- return
- }
- b := p.buf[i]
- i++
- x |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- p.index = i
- return
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- err = errOverflow
- return
-}
-
-// DecodeVarint reads a varint-encoded integer from the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) DecodeVarint() (x uint64, err error) {
- i := p.index
- buf := p.buf
-
- if i >= len(buf) {
- return 0, io.ErrUnexpectedEOF
- } else if buf[i] < 0x80 {
- p.index++
- return uint64(buf[i]), nil
- } else if len(buf)-i < 10 {
- return p.decodeVarintSlow()
- }
-
- var b uint64
- // we already checked the first byte
- x = uint64(buf[i]) - 0x80
- i++
-
- b = uint64(buf[i])
- i++
- x += b << 7
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 7
-
- b = uint64(buf[i])
- i++
- x += b << 14
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 14
-
- b = uint64(buf[i])
- i++
- x += b << 21
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 21
-
- b = uint64(buf[i])
- i++
- x += b << 28
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 28
-
- b = uint64(buf[i])
- i++
- x += b << 35
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 35
-
- b = uint64(buf[i])
- i++
- x += b << 42
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 42
-
- b = uint64(buf[i])
- i++
- x += b << 49
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 49
-
- b = uint64(buf[i])
- i++
- x += b << 56
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 56
-
- b = uint64(buf[i])
- i++
- x += b << 63
- if b&0x80 == 0 {
- goto done
- }
-
- return 0, errOverflow
-
-done:
- p.index = i
- return x, nil
-}
-
-// DecodeFixed64 reads a 64-bit integer from the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) DecodeFixed64() (x uint64, err error) {
- // x, err already 0
- i := p.index + 8
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-8])
- x |= uint64(p.buf[i-7]) << 8
- x |= uint64(p.buf[i-6]) << 16
- x |= uint64(p.buf[i-5]) << 24
- x |= uint64(p.buf[i-4]) << 32
- x |= uint64(p.buf[i-3]) << 40
- x |= uint64(p.buf[i-2]) << 48
- x |= uint64(p.buf[i-1]) << 56
- return
-}
-
-// DecodeFixed32 reads a 32-bit integer from the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) DecodeFixed32() (x uint64, err error) {
- // x, err already 0
- i := p.index + 4
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-4])
- x |= uint64(p.buf[i-3]) << 8
- x |= uint64(p.buf[i-2]) << 16
- x |= uint64(p.buf[i-1]) << 24
- return
-}
-
-// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
-// from the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
- return
-}
-
-// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
-// from the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
- return
-}
-
-// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
- n, err := p.DecodeVarint()
- if err != nil {
- return nil, err
- }
-
- nb := int(n)
- if nb < 0 {
- return nil, fmt.Errorf("proto: bad byte length %d", nb)
- }
- end := p.index + nb
- if end < p.index || end > len(p.buf) {
- return nil, io.ErrUnexpectedEOF
- }
-
- if !alloc {
- // todo: check if can get more uses of alloc=false
- buf = p.buf[p.index:end]
- p.index += nb
- return
- }
-
- buf = make([]byte, nb)
- copy(buf, p.buf[p.index:])
- p.index += nb
- return
-}
-
-// DecodeStringBytes reads an encoded string from the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) DecodeStringBytes() (s string, err error) {
- buf, err := p.DecodeRawBytes(false)
- if err != nil {
- return
- }
- return string(buf), nil
-}
-
-// Unmarshaler is the interface representing objects that can
-// unmarshal themselves. The argument points to data that may be
-// overwritten, so implementations should not keep references to the
-// buffer.
-// Unmarshal implementations should not clear the receiver.
-// Any unmarshaled data should be merged into the receiver.
-// Callers of Unmarshal that do not want to retain existing data
-// should Reset the receiver before calling Unmarshal.
-type Unmarshaler interface {
- Unmarshal([]byte) error
-}
-
-// newUnmarshaler is the interface representing objects that can
-// unmarshal themselves. The semantics are identical to Unmarshaler.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newUnmarshaler interface {
- XXX_Unmarshal([]byte) error
-}
-
-// Unmarshal parses the protocol buffer representation in buf and places the
-// decoded result in pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// Unmarshal resets pb before starting to unmarshal, so any
-// existing data in pb is always removed. Use UnmarshalMerge
-// to preserve and append to existing data.
-func Unmarshal(buf []byte, pb Message) error {
- pb.Reset()
- if u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// UnmarshalMerge parses the protocol buffer representation in buf and
-// writes the decoded result to pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// UnmarshalMerge merges into existing data in pb.
-// Most code should use Unmarshal instead.
-func UnmarshalMerge(buf []byte, pb Message) error {
- if u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// DecodeMessage reads a count-delimited message from the Buffer.
-func (p *Buffer) DecodeMessage(pb Message) error {
- enc, err := p.DecodeRawBytes(false)
- if err != nil {
- return err
- }
- return NewBuffer(enc).Unmarshal(pb)
-}
-
-// DecodeGroup reads a tag-delimited group from the Buffer.
-// StartGroup tag is already consumed. This function consumes
-// EndGroup tag.
-func (p *Buffer) DecodeGroup(pb Message) error {
- b := p.buf[p.index:]
- x, y := findEndGroup(b)
- if x < 0 {
- return io.ErrUnexpectedEOF
- }
- err := Unmarshal(b[:x], pb)
- p.index += y
- return err
-}
-
-// Unmarshal parses the protocol buffer representation in the
-// Buffer and places the decoded result in pb. If the struct
-// underlying pb does not match the data in the buffer, the results can be
-// unpredictable.
-//
-// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
-func (p *Buffer) Unmarshal(pb Message) error {
- // If the object can unmarshal itself, let it.
- if u, ok := pb.(newUnmarshaler); ok {
- err := u.XXX_Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- err := u.Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
-
- // Slow workaround for messages that aren't Unmarshalers.
- // This includes some hand-coded .pb.go files and
- // bootstrap protos.
- // TODO: fix all of those and then add Unmarshal to
- // the Message interface. Then:
- // The cast above and code below can be deleted.
- // The old unmarshaler can be deleted.
- // Clients can call Unmarshal directly (can already do that, actually).
- var info InternalMessageInfo
- err := info.Unmarshal(pb, p.buf[p.index:])
- p.index = len(p.buf)
- return err
-}
diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go
deleted file mode 100644
index 35b882c..0000000
--- a/vendor/github.com/golang/protobuf/proto/deprecated.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-import "errors"
-
-// Deprecated: do not use.
-type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 }
-
-// Deprecated: do not use.
-func GetStats() Stats { return Stats{} }
-
-// Deprecated: do not use.
-func MarshalMessageSet(interface{}) ([]byte, error) {
- return nil, errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func UnmarshalMessageSet([]byte, interface{}) error {
- return errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func MarshalMessageSetJSON(interface{}) ([]byte, error) {
- return nil, errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func UnmarshalMessageSetJSON([]byte, interface{}) error {
- return errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func RegisterMessageSetType(Message, int32, string) {}
diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go
deleted file mode 100644
index dea2617..0000000
--- a/vendor/github.com/golang/protobuf/proto/discard.go
+++ /dev/null
@@ -1,350 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-import (
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-type generatedDiscarder interface {
- XXX_DiscardUnknown()
-}
-
-// DiscardUnknown recursively discards all unknown fields from this message
-// and all embedded messages.
-//
-// When unmarshaling a message with unrecognized fields, the tags and values
-// of such fields are preserved in the Message. This allows a later call to
-// marshal to be able to produce a message that continues to have those
-// unrecognized fields. To avoid this, DiscardUnknown is used to
-// explicitly clear the unknown fields after unmarshaling.
-//
-// For proto2 messages, the unknown fields of message extensions are only
-// discarded from messages that have been accessed via GetExtension.
-func DiscardUnknown(m Message) {
- if m, ok := m.(generatedDiscarder); ok {
- m.XXX_DiscardUnknown()
- return
- }
- // TODO: Dynamically populate a InternalMessageInfo for legacy messages,
- // but the master branch has no implementation for InternalMessageInfo,
- // so it would be more work to replicate that approach.
- discardLegacy(m)
-}
-
-// DiscardUnknown recursively discards all unknown fields.
-func (a *InternalMessageInfo) DiscardUnknown(m Message) {
- di := atomicLoadDiscardInfo(&a.discard)
- if di == nil {
- di = getDiscardInfo(reflect.TypeOf(m).Elem())
- atomicStoreDiscardInfo(&a.discard, di)
- }
- di.discard(toPointer(&m))
-}
-
-type discardInfo struct {
- typ reflect.Type
-
- initialized int32 // 0: only typ is valid, 1: everything is valid
- lock sync.Mutex
-
- fields []discardFieldInfo
- unrecognized field
-}
-
-type discardFieldInfo struct {
- field field // Offset of field, guaranteed to be valid
- discard func(src pointer)
-}
-
-var (
- discardInfoMap = map[reflect.Type]*discardInfo{}
- discardInfoLock sync.Mutex
-)
-
-func getDiscardInfo(t reflect.Type) *discardInfo {
- discardInfoLock.Lock()
- defer discardInfoLock.Unlock()
- di := discardInfoMap[t]
- if di == nil {
- di = &discardInfo{typ: t}
- discardInfoMap[t] = di
- }
- return di
-}
-
-func (di *discardInfo) discard(src pointer) {
- if src.isNil() {
- return // Nothing to do.
- }
-
- if atomic.LoadInt32(&di.initialized) == 0 {
- di.computeDiscardInfo()
- }
-
- for _, fi := range di.fields {
- sfp := src.offset(fi.field)
- fi.discard(sfp)
- }
-
- // For proto2 messages, only discard unknown fields in message extensions
- // that have been accessed via GetExtension.
- if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
- // Ignore lock since DiscardUnknown is not concurrency safe.
- emm, _ := em.extensionsRead()
- for _, mx := range emm {
- if m, ok := mx.value.(Message); ok {
- DiscardUnknown(m)
- }
- }
- }
-
- if di.unrecognized.IsValid() {
- *src.offset(di.unrecognized).toBytes() = nil
- }
-}
-
-func (di *discardInfo) computeDiscardInfo() {
- di.lock.Lock()
- defer di.lock.Unlock()
- if di.initialized != 0 {
- return
- }
- t := di.typ
- n := t.NumField()
-
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
-
- dfi := discardFieldInfo{field: toField(&f)}
- tf := f.Type
-
- // Unwrap tf to get its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
- }
-
- switch tf.Kind() {
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
- case isSlice: // E.g., []*pb.T
- di := getDiscardInfo(tf)
- dfi.discard = func(src pointer) {
- sps := src.getPointerSlice()
- for _, sp := range sps {
- if !sp.isNil() {
- di.discard(sp)
- }
- }
- }
- default: // E.g., *pb.T
- di := getDiscardInfo(tf)
- dfi.discard = func(src pointer) {
- sp := src.getPointer()
- if !sp.isNil() {
- di.discard(sp)
- }
- }
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
- default: // E.g., map[K]V
- if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
- dfi.discard = func(src pointer) {
- sm := src.asPointerTo(tf).Elem()
- if sm.Len() == 0 {
- return
- }
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- DiscardUnknown(val.Interface().(Message))
- }
- }
- } else {
- dfi.discard = func(pointer) {} // Noop
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
- default: // E.g., interface{}
- // TODO: Make this faster?
- dfi.discard = func(src pointer) {
- su := src.asPointerTo(tf).Elem()
- if !su.IsNil() {
- sv := su.Elem().Elem().Field(0)
- if sv.Kind() == reflect.Ptr && sv.IsNil() {
- return
- }
- switch sv.Type().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- DiscardUnknown(sv.Interface().(Message))
- }
- }
- }
- }
- default:
- continue
- }
- di.fields = append(di.fields, dfi)
- }
-
- di.unrecognized = invalidField
- if f, ok := t.FieldByName("XXX_unrecognized"); ok {
- if f.Type != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- di.unrecognized = toField(&f)
- }
-
- atomic.StoreInt32(&di.initialized, 1)
-}
-
-func discardLegacy(m Message) {
- v := reflect.ValueOf(m)
- if v.Kind() != reflect.Ptr || v.IsNil() {
- return
- }
- v = v.Elem()
- if v.Kind() != reflect.Struct {
- return
- }
- t := v.Type()
-
- for i := 0; i < v.NumField(); i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- vf := v.Field(i)
- tf := f.Type
-
- // Unwrap tf to get its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
- }
-
- switch tf.Kind() {
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
- case isSlice: // E.g., []*pb.T
- for j := 0; j < vf.Len(); j++ {
- discardLegacy(vf.Index(j).Interface().(Message))
- }
- default: // E.g., *pb.T
- discardLegacy(vf.Interface().(Message))
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
- default: // E.g., map[K]V
- tv := vf.Type().Elem()
- if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
- for _, key := range vf.MapKeys() {
- val := vf.MapIndex(key)
- discardLegacy(val.Interface().(Message))
- }
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
- default: // E.g., test_proto.isCommunique_Union interface
- if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
- vf = vf.Elem() // E.g., *test_proto.Communique_Msg
- if !vf.IsNil() {
- vf = vf.Elem() // E.g., test_proto.Communique_Msg
- vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
- if vf.Kind() == reflect.Ptr {
- discardLegacy(vf.Interface().(Message))
- }
- }
- }
- }
- }
- }
-
- if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
- if vf.Type() != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- vf.Set(reflect.ValueOf([]byte(nil)))
- }
-
- // For proto2 messages, only discard unknown fields in message extensions
- // that have been accessed via GetExtension.
- if em, err := extendable(m); err == nil {
- // Ignore lock since discardLegacy is not concurrency safe.
- emm, _ := em.extensionsRead()
- for _, mx := range emm {
- if m, ok := mx.value.(Message); ok {
- discardLegacy(m)
- }
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go
deleted file mode 100644
index 3abfed2..0000000
--- a/vendor/github.com/golang/protobuf/proto/encode.go
+++ /dev/null
@@ -1,203 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
-import (
- "errors"
- "reflect"
-)
-
-var (
- // errRepeatedHasNil is the error returned if Marshal is called with
- // a struct with a repeated field containing a nil element.
- errRepeatedHasNil = errors.New("proto: repeated field has nil element")
-
- // errOneofHasNil is the error returned if Marshal is called with
- // a struct with a oneof field containing a nil element.
- errOneofHasNil = errors.New("proto: oneof field has nil value")
-
- // ErrNil is the error returned if Marshal is called with nil.
- ErrNil = errors.New("proto: Marshal called with nil")
-
- // ErrTooLarge is the error returned if Marshal is called with a
- // message that encodes to >2GB.
- ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
-)
-
-// The fundamental encoders that put bytes on the wire.
-// Those that take integer types all accept uint64 and are
-// therefore of type valueEncoder.
-
-const maxVarintBytes = 10 // maximum length of a varint
-
-// EncodeVarint returns the varint encoding of x.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-// Not used by the package itself, but helpful to clients
-// wishing to use the same encoding.
-func EncodeVarint(x uint64) []byte {
- var buf [maxVarintBytes]byte
- var n int
- for n = 0; x > 127; n++ {
- buf[n] = 0x80 | uint8(x&0x7F)
- x >>= 7
- }
- buf[n] = uint8(x)
- n++
- return buf[0:n]
-}
-
-// EncodeVarint writes a varint-encoded integer to the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) EncodeVarint(x uint64) error {
- for x >= 1<<7 {
- p.buf = append(p.buf, uint8(x&0x7f|0x80))
- x >>= 7
- }
- p.buf = append(p.buf, uint8(x))
- return nil
-}
-
-// SizeVarint returns the varint encoding size of an integer.
-func SizeVarint(x uint64) int {
- switch {
- case x < 1<<7:
- return 1
- case x < 1<<14:
- return 2
- case x < 1<<21:
- return 3
- case x < 1<<28:
- return 4
- case x < 1<<35:
- return 5
- case x < 1<<42:
- return 6
- case x < 1<<49:
- return 7
- case x < 1<<56:
- return 8
- case x < 1<<63:
- return 9
- }
- return 10
-}
-
-// EncodeFixed64 writes a 64-bit integer to the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) EncodeFixed64(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24),
- uint8(x>>32),
- uint8(x>>40),
- uint8(x>>48),
- uint8(x>>56))
- return nil
-}
-
-// EncodeFixed32 writes a 32-bit integer to the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) EncodeFixed32(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24))
- return nil
-}
-
-// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
-// to the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) EncodeZigzag64(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-
-// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
-// to the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) EncodeZigzag32(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
-}
-
-// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) EncodeRawBytes(b []byte) error {
- p.EncodeVarint(uint64(len(b)))
- p.buf = append(p.buf, b...)
- return nil
-}
-
-// EncodeStringBytes writes an encoded string to the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) EncodeStringBytes(s string) error {
- p.EncodeVarint(uint64(len(s)))
- p.buf = append(p.buf, s...)
- return nil
-}
-
-// Marshaler is the interface representing objects that can marshal themselves.
-type Marshaler interface {
- Marshal() ([]byte, error)
-}
-
-// EncodeMessage writes the protocol buffer to the Buffer,
-// prefixed by a varint-encoded length.
-func (p *Buffer) EncodeMessage(pb Message) error {
- siz := Size(pb)
- p.EncodeVarint(uint64(siz))
- return p.Marshal(pb)
-}
-
-// All protocol buffer fields are nillable, but be careful.
-func isNil(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
- return v.IsNil()
- }
- return false
-}
diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go
deleted file mode 100644
index f9b6e41..0000000
--- a/vendor/github.com/golang/protobuf/proto/equal.go
+++ /dev/null
@@ -1,301 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-// Protocol buffer comparison.
-
-package proto
-
-import (
- "bytes"
- "log"
- "reflect"
- "strings"
-)
-
-/*
-Equal returns true iff protocol buffers a and b are equal.
-The arguments must both be pointers to protocol buffer structs.
-
-Equality is defined in this way:
- - Two messages are equal iff they are the same type,
- corresponding fields are equal, unknown field sets
- are equal, and extensions sets are equal.
- - Two set scalar fields are equal iff their values are equal.
- If the fields are of a floating-point type, remember that
- NaN != x for all x, including NaN. If the message is defined
- in a proto3 .proto file, fields are not "set"; specifically,
- zero length proto3 "bytes" fields are equal (nil == {}).
- - Two repeated fields are equal iff their lengths are the same,
- and their corresponding elements are equal. Note a "bytes" field,
- although represented by []byte, is not a repeated field and the
- rule for the scalar fields described above applies.
- - Two unset fields are equal.
- - Two unknown field sets are equal if their current
- encoded state is equal.
- - Two extension sets are equal iff they have corresponding
- elements that are pairwise equal.
- - Two map fields are equal iff their lengths are the same,
- and they contain the same set of elements. Zero-length map
- fields are equal.
- - Every other combination of things are not equal.
-
-The return value is undefined if a and b are not protocol buffers.
-*/
-func Equal(a, b Message) bool {
- if a == nil || b == nil {
- return a == b
- }
- v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
- if v1.Type() != v2.Type() {
- return false
- }
- if v1.Kind() == reflect.Ptr {
- if v1.IsNil() {
- return v2.IsNil()
- }
- if v2.IsNil() {
- return false
- }
- v1, v2 = v1.Elem(), v2.Elem()
- }
- if v1.Kind() != reflect.Struct {
- return false
- }
- return equalStruct(v1, v2)
-}
-
-// v1 and v2 are known to have the same type.
-func equalStruct(v1, v2 reflect.Value) bool {
- sprop := GetProperties(v1.Type())
- for i := 0; i < v1.NumField(); i++ {
- f := v1.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- f1, f2 := v1.Field(i), v2.Field(i)
- if f.Type.Kind() == reflect.Ptr {
- if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
- // both unset
- continue
- } else if n1 != n2 {
- // set/unset mismatch
- return false
- }
- f1, f2 = f1.Elem(), f2.Elem()
- }
- if !equalAny(f1, f2, sprop.Prop[i]) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_InternalExtensions")
- if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_extensions")
- if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
- return false
- }
- }
-
- uf := v1.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return true
- }
-
- u1 := uf.Bytes()
- u2 := v2.FieldByName("XXX_unrecognized").Bytes()
- return bytes.Equal(u1, u2)
-}
-
-// v1 and v2 are known to have the same type.
-// prop may be nil.
-func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
- if v1.Type() == protoMessageType {
- m1, _ := v1.Interface().(Message)
- m2, _ := v2.Interface().(Message)
- return Equal(m1, m2)
- }
- switch v1.Kind() {
- case reflect.Bool:
- return v1.Bool() == v2.Bool()
- case reflect.Float32, reflect.Float64:
- return v1.Float() == v2.Float()
- case reflect.Int32, reflect.Int64:
- return v1.Int() == v2.Int()
- case reflect.Interface:
- // Probably a oneof field; compare the inner values.
- n1, n2 := v1.IsNil(), v2.IsNil()
- if n1 || n2 {
- return n1 == n2
- }
- e1, e2 := v1.Elem(), v2.Elem()
- if e1.Type() != e2.Type() {
- return false
- }
- return equalAny(e1, e2, nil)
- case reflect.Map:
- if v1.Len() != v2.Len() {
- return false
- }
- for _, key := range v1.MapKeys() {
- val2 := v2.MapIndex(key)
- if !val2.IsValid() {
- // This key was not found in the second map.
- return false
- }
- if !equalAny(v1.MapIndex(key), val2, nil) {
- return false
- }
- }
- return true
- case reflect.Ptr:
- // Maps may have nil values in them, so check for nil.
- if v1.IsNil() && v2.IsNil() {
- return true
- }
- if v1.IsNil() != v2.IsNil() {
- return false
- }
- return equalAny(v1.Elem(), v2.Elem(), prop)
- case reflect.Slice:
- if v1.Type().Elem().Kind() == reflect.Uint8 {
- // short circuit: []byte
-
- // Edge case: if this is in a proto3 message, a zero length
- // bytes field is considered the zero value.
- if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
- return true
- }
- if v1.IsNil() != v2.IsNil() {
- return false
- }
- return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
- }
-
- if v1.Len() != v2.Len() {
- return false
- }
- for i := 0; i < v1.Len(); i++ {
- if !equalAny(v1.Index(i), v2.Index(i), prop) {
- return false
- }
- }
- return true
- case reflect.String:
- return v1.Interface().(string) == v2.Interface().(string)
- case reflect.Struct:
- return equalStruct(v1, v2)
- case reflect.Uint32, reflect.Uint64:
- return v1.Uint() == v2.Uint()
- }
-
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to compare %v", v1)
- return false
-}
-
-// base is the struct type that the extensions are based on.
-// x1 and x2 are InternalExtensions.
-func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
- em1, _ := x1.extensionsRead()
- em2, _ := x2.extensionsRead()
- return equalExtMap(base, em1, em2)
-}
-
-func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
- if len(em1) != len(em2) {
- return false
- }
-
- for extNum, e1 := range em1 {
- e2, ok := em2[extNum]
- if !ok {
- return false
- }
-
- m1 := extensionAsLegacyType(e1.value)
- m2 := extensionAsLegacyType(e2.value)
-
- if m1 == nil && m2 == nil {
- // Both have only encoded form.
- if bytes.Equal(e1.enc, e2.enc) {
- continue
- }
- // The bytes are different, but the extensions might still be
- // equal. We need to decode them to compare.
- }
-
- if m1 != nil && m2 != nil {
- // Both are unencoded.
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
- return false
- }
- continue
- }
-
- // At least one is encoded. To do a semantically correct comparison
- // we need to unmarshal them first.
- var desc *ExtensionDesc
- if m := extensionMaps[base]; m != nil {
- desc = m[extNum]
- }
- if desc == nil {
- // If both have only encoded form and the bytes are the same,
- // it is handled above. We get here when the bytes are different.
- // We don't know how to decode it, so just compare them as byte
- // slices.
- log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
- return false
- }
- var err error
- if m1 == nil {
- m1, err = decodeExtension(e1.enc, desc)
- }
- if m2 == nil && err == nil {
- m2, err = decodeExtension(e2.enc, desc)
- }
- if err != nil {
- // The encoded form is invalid.
- log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
- return false
- }
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
- return false
- }
- }
-
- return true
-}
diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go
deleted file mode 100644
index fa88add..0000000
--- a/vendor/github.com/golang/protobuf/proto/extensions.go
+++ /dev/null
@@ -1,607 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-/*
- * Types and routines for supporting protocol buffer extensions.
- */
-
-import (
- "errors"
- "fmt"
- "io"
- "reflect"
- "strconv"
- "sync"
-)
-
-// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
-var ErrMissingExtension = errors.New("proto: missing extension")
-
-// ExtensionRange represents a range of message extensions for a protocol buffer.
-// Used in code generated by the protocol compiler.
-type ExtensionRange struct {
- Start, End int32 // both inclusive
-}
-
-// extendableProto is an interface implemented by any protocol buffer generated by the current
-// proto compiler that may be extended.
-type extendableProto interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- extensionsWrite() map[int32]Extension
- extensionsRead() (map[int32]Extension, sync.Locker)
-}
-
-// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
-// version of the proto compiler that may be extended.
-type extendableProtoV1 interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- ExtensionMap() map[int32]Extension
-}
-
-// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
-type extensionAdapter struct {
- extendableProtoV1
-}
-
-func (e extensionAdapter) extensionsWrite() map[int32]Extension {
- return e.ExtensionMap()
-}
-
-func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
- return e.ExtensionMap(), notLocker{}
-}
-
-// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
-type notLocker struct{}
-
-func (n notLocker) Lock() {}
-func (n notLocker) Unlock() {}
-
-// extendable returns the extendableProto interface for the given generated proto message.
-// If the proto message has the old extension format, it returns a wrapper that implements
-// the extendableProto interface.
-func extendable(p interface{}) (extendableProto, error) {
- switch p := p.(type) {
- case extendableProto:
- if isNilPtr(p) {
- return nil, fmt.Errorf("proto: nil %T is not extendable", p)
- }
- return p, nil
- case extendableProtoV1:
- if isNilPtr(p) {
- return nil, fmt.Errorf("proto: nil %T is not extendable", p)
- }
- return extensionAdapter{p}, nil
- }
- // Don't allocate a specific error containing %T:
- // this is the hot path for Clone and MarshalText.
- return nil, errNotExtendable
-}
-
-var errNotExtendable = errors.New("proto: not an extendable proto.Message")
-
-func isNilPtr(x interface{}) bool {
- v := reflect.ValueOf(x)
- return v.Kind() == reflect.Ptr && v.IsNil()
-}
-
-// XXX_InternalExtensions is an internal representation of proto extensions.
-//
-// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
-// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
-//
-// The methods of XXX_InternalExtensions are not concurrency safe in general,
-// but calls to logically read-only methods such as has and get may be executed concurrently.
-type XXX_InternalExtensions struct {
- // The struct must be indirect so that if a user inadvertently copies a
- // generated message and its embedded XXX_InternalExtensions, they
- // avoid the mayhem of a copied mutex.
- //
- // The mutex serializes all logically read-only operations to p.extensionMap.
- // It is up to the client to ensure that write operations to p.extensionMap are
- // mutually exclusive with other accesses.
- p *struct {
- mu sync.Mutex
- extensionMap map[int32]Extension
- }
-}
-
-// extensionsWrite returns the extension map, creating it on first use.
-func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
- if e.p == nil {
- e.p = new(struct {
- mu sync.Mutex
- extensionMap map[int32]Extension
- })
- e.p.extensionMap = make(map[int32]Extension)
- }
- return e.p.extensionMap
-}
-
-// extensionsRead returns the extensions map for read-only use. It may be nil.
-// The caller must hold the returned mutex's lock when accessing Elements within the map.
-func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
- if e.p == nil {
- return nil, nil
- }
- return e.p.extensionMap, &e.p.mu
-}
-
-// ExtensionDesc represents an extension specification.
-// Used in generated code from the protocol compiler.
-type ExtensionDesc struct {
- ExtendedType Message // nil pointer to the type that is being extended
- ExtensionType interface{} // nil pointer to the extension type
- Field int32 // field number
- Name string // fully-qualified name of extension, for text formatting
- Tag string // protobuf tag style
- Filename string // name of the file in which the extension is defined
-}
-
-func (ed *ExtensionDesc) repeated() bool {
- t := reflect.TypeOf(ed.ExtensionType)
- return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
-}
-
-// Extension represents an extension in a message.
-type Extension struct {
- // When an extension is stored in a message using SetExtension
- // only desc and value are set. When the message is marshaled
- // enc will be set to the encoded form of the message.
- //
- // When a message is unmarshaled and contains extensions, each
- // extension will have only enc set. When such an extension is
- // accessed using GetExtension (or GetExtensions) desc and value
- // will be set.
- desc *ExtensionDesc
-
- // value is a concrete value for the extension field. Let the type of
- // desc.ExtensionType be the "API type" and the type of Extension.value
- // be the "storage type". The API type and storage type are the same except:
- // * For scalars (except []byte), the API type uses *T,
- // while the storage type uses T.
- // * For repeated fields, the API type uses []T, while the storage type
- // uses *[]T.
- //
- // The reason for the divergence is so that the storage type more naturally
- // matches what is expected of when retrieving the values through the
- // protobuf reflection APIs.
- //
- // The value may only be populated if desc is also populated.
- value interface{}
-
- // enc is the raw bytes for the extension field.
- enc []byte
-}
-
-// SetRawExtension is for testing only.
-func SetRawExtension(base Message, id int32, b []byte) {
- epb, err := extendable(base)
- if err != nil {
- return
- }
- extmap := epb.extensionsWrite()
- extmap[id] = Extension{enc: b}
-}
-
-// isExtensionField returns true iff the given field number is in an extension range.
-func isExtensionField(pb extendableProto, field int32) bool {
- for _, er := range pb.ExtensionRangeArray() {
- if er.Start <= field && field <= er.End {
- return true
- }
- }
- return false
-}
-
-// checkExtensionTypes checks that the given extension is valid for pb.
-func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
- var pbi interface{} = pb
- // Check the extended type.
- if ea, ok := pbi.(extensionAdapter); ok {
- pbi = ea.extendableProtoV1
- }
- if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
- return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
- }
- // Check the range.
- if !isExtensionField(pb, extension.Field) {
- return errors.New("proto: bad extension number; not in declared ranges")
- }
- return nil
-}
-
-// extPropKey is sufficient to uniquely identify an extension.
-type extPropKey struct {
- base reflect.Type
- field int32
-}
-
-var extProp = struct {
- sync.RWMutex
- m map[extPropKey]*Properties
-}{
- m: make(map[extPropKey]*Properties),
-}
-
-func extensionProperties(ed *ExtensionDesc) *Properties {
- key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
-
- extProp.RLock()
- if prop, ok := extProp.m[key]; ok {
- extProp.RUnlock()
- return prop
- }
- extProp.RUnlock()
-
- extProp.Lock()
- defer extProp.Unlock()
- // Check again.
- if prop, ok := extProp.m[key]; ok {
- return prop
- }
-
- prop := new(Properties)
- prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
- extProp.m[key] = prop
- return prop
-}
-
-// HasExtension returns whether the given extension is present in pb.
-func HasExtension(pb Message, extension *ExtensionDesc) bool {
- // TODO: Check types, field numbers, etc.?
- epb, err := extendable(pb)
- if err != nil {
- return false
- }
- extmap, mu := epb.extensionsRead()
- if extmap == nil {
- return false
- }
- mu.Lock()
- _, ok := extmap[extension.Field]
- mu.Unlock()
- return ok
-}
-
-// ClearExtension removes the given extension from pb.
-func ClearExtension(pb Message, extension *ExtensionDesc) {
- epb, err := extendable(pb)
- if err != nil {
- return
- }
- // TODO: Check types, field numbers, etc.?
- extmap := epb.extensionsWrite()
- delete(extmap, extension.Field)
-}
-
-// GetExtension retrieves a proto2 extended field from pb.
-//
-// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
-// then GetExtension parses the encoded field and returns a Go value of the specified type.
-// If the field is not present, then the default value is returned (if one is specified),
-// otherwise ErrMissingExtension is reported.
-//
-// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
-// then GetExtension returns the raw encoded bytes of the field extension.
-func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
-
- if extension.ExtendedType != nil {
- // can only check type if this is a complete descriptor
- if err := checkExtensionTypes(epb, extension); err != nil {
- return nil, err
- }
- }
-
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return defaultExtensionValue(extension)
- }
- mu.Lock()
- defer mu.Unlock()
- e, ok := emap[extension.Field]
- if !ok {
- // defaultExtensionValue returns the default value or
- // ErrMissingExtension if there is no default.
- return defaultExtensionValue(extension)
- }
-
- if e.value != nil {
- // Already decoded. Check the descriptor, though.
- if e.desc != extension {
- // This shouldn't happen. If it does, it means that
- // GetExtension was called twice with two different
- // descriptors with the same field number.
- return nil, errors.New("proto: descriptor conflict")
- }
- return extensionAsLegacyType(e.value), nil
- }
-
- if extension.ExtensionType == nil {
- // incomplete descriptor
- return e.enc, nil
- }
-
- v, err := decodeExtension(e.enc, extension)
- if err != nil {
- return nil, err
- }
-
- // Remember the decoded version and drop the encoded version.
- // That way it is safe to mutate what we return.
- e.value = extensionAsStorageType(v)
- e.desc = extension
- e.enc = nil
- emap[extension.Field] = e
- return extensionAsLegacyType(e.value), nil
-}
-
-// defaultExtensionValue returns the default value for extension.
-// If no default for an extension is defined ErrMissingExtension is returned.
-func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
- if extension.ExtensionType == nil {
- // incomplete descriptor, so no default
- return nil, ErrMissingExtension
- }
-
- t := reflect.TypeOf(extension.ExtensionType)
- props := extensionProperties(extension)
-
- sf, _, err := fieldDefault(t, props)
- if err != nil {
- return nil, err
- }
-
- if sf == nil || sf.value == nil {
- // There is no default value.
- return nil, ErrMissingExtension
- }
-
- if t.Kind() != reflect.Ptr {
- // We do not need to return a Ptr, we can directly return sf.value.
- return sf.value, nil
- }
-
- // We need to return an interface{} that is a pointer to sf.value.
- value := reflect.New(t).Elem()
- value.Set(reflect.New(value.Type().Elem()))
- if sf.kind == reflect.Int32 {
- // We may have an int32 or an enum, but the underlying data is int32.
- // Since we can't set an int32 into a non int32 reflect.value directly
- // set it as a int32.
- value.Elem().SetInt(int64(sf.value.(int32)))
- } else {
- value.Elem().Set(reflect.ValueOf(sf.value))
- }
- return value.Interface(), nil
-}
-
-// decodeExtension decodes an extension encoded in b.
-func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
- t := reflect.TypeOf(extension.ExtensionType)
- unmarshal := typeUnmarshaler(t, extension.Tag)
-
- // t is a pointer to a struct, pointer to basic type or a slice.
- // Allocate space to store the pointer/slice.
- value := reflect.New(t).Elem()
-
- var err error
- for {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- wire := int(x) & 7
-
- b, err = unmarshal(b, valToPointer(value.Addr()), wire)
- if err != nil {
- return nil, err
- }
-
- if len(b) == 0 {
- break
- }
- }
- return value.Interface(), nil
-}
-
-// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
-// The returned slice has the same length as es; missing extensions will appear as nil elements.
-func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
- extensions = make([]interface{}, len(es))
- for i, e := range es {
- extensions[i], err = GetExtension(epb, e)
- if err == ErrMissingExtension {
- err = nil
- }
- if err != nil {
- return
- }
- }
- return
-}
-
-// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
-// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
-// just the Field field, which defines the extension's field number.
-func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
- registeredExtensions := RegisteredExtensions(pb)
-
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return nil, nil
- }
- mu.Lock()
- defer mu.Unlock()
- extensions := make([]*ExtensionDesc, 0, len(emap))
- for extid, e := range emap {
- desc := e.desc
- if desc == nil {
- desc = registeredExtensions[extid]
- if desc == nil {
- desc = &ExtensionDesc{Field: extid}
- }
- }
-
- extensions = append(extensions, desc)
- }
- return extensions, nil
-}
-
-// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
- epb, err := extendable(pb)
- if err != nil {
- return err
- }
- if err := checkExtensionTypes(epb, extension); err != nil {
- return err
- }
- typ := reflect.TypeOf(extension.ExtensionType)
- if typ != reflect.TypeOf(value) {
- return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType)
- }
- // nil extension values need to be caught early, because the
- // encoder can't distinguish an ErrNil due to a nil extension
- // from an ErrNil due to a missing field. Extensions are
- // always optional, so the encoder would just swallow the error
- // and drop all the extensions from the encoded message.
- if reflect.ValueOf(value).IsNil() {
- return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
- }
-
- extmap := epb.extensionsWrite()
- extmap[extension.Field] = Extension{desc: extension, value: extensionAsStorageType(value)}
- return nil
-}
-
-// ClearAllExtensions clears all extensions from pb.
-func ClearAllExtensions(pb Message) {
- epb, err := extendable(pb)
- if err != nil {
- return
- }
- m := epb.extensionsWrite()
- for k := range m {
- delete(m, k)
- }
-}
-
-// A global registry of extensions.
-// The generated code will register the generated descriptors by calling RegisterExtension.
-
-var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
-
-// RegisterExtension is called from the generated code.
-func RegisterExtension(desc *ExtensionDesc) {
- st := reflect.TypeOf(desc.ExtendedType).Elem()
- m := extensionMaps[st]
- if m == nil {
- m = make(map[int32]*ExtensionDesc)
- extensionMaps[st] = m
- }
- if _, ok := m[desc.Field]; ok {
- panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
- }
- m[desc.Field] = desc
-}
-
-// RegisteredExtensions returns a map of the registered extensions of a
-// protocol buffer struct, indexed by the extension number.
-// The argument pb should be a nil pointer to the struct type.
-func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
- return extensionMaps[reflect.TypeOf(pb).Elem()]
-}
-
-// extensionAsLegacyType converts an value in the storage type as the API type.
-// See Extension.value.
-func extensionAsLegacyType(v interface{}) interface{} {
- switch rv := reflect.ValueOf(v); rv.Kind() {
- case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
- // Represent primitive types as a pointer to the value.
- rv2 := reflect.New(rv.Type())
- rv2.Elem().Set(rv)
- v = rv2.Interface()
- case reflect.Ptr:
- // Represent slice types as the value itself.
- switch rv.Type().Elem().Kind() {
- case reflect.Slice:
- if rv.IsNil() {
- v = reflect.Zero(rv.Type().Elem()).Interface()
- } else {
- v = rv.Elem().Interface()
- }
- }
- }
- return v
-}
-
-// extensionAsStorageType converts an value in the API type as the storage type.
-// See Extension.value.
-func extensionAsStorageType(v interface{}) interface{} {
- switch rv := reflect.ValueOf(v); rv.Kind() {
- case reflect.Ptr:
- // Represent slice types as the value itself.
- switch rv.Type().Elem().Kind() {
- case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
- if rv.IsNil() {
- v = reflect.Zero(rv.Type().Elem()).Interface()
- } else {
- v = rv.Elem().Interface()
- }
- }
- case reflect.Slice:
- // Represent slice types as a pointer to the value.
- if rv.Type().Elem().Kind() != reflect.Uint8 {
- rv2 := reflect.New(rv.Type())
- rv2.Elem().Set(rv)
- v = rv2.Interface()
- }
- }
- return v
-}
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
deleted file mode 100644
index fdd328b..0000000
--- a/vendor/github.com/golang/protobuf/proto/lib.go
+++ /dev/null
@@ -1,965 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-/*
-Package proto converts data structures to and from the wire format of
-protocol buffers. It works in concert with the Go source code generated
-for .proto files by the protocol compiler.
-
-A summary of the properties of the protocol buffer interface
-for a protocol buffer variable v:
-
- - Names are turned from camel_case to CamelCase for export.
- - There are no methods on v to set fields; just treat
- them as structure fields.
- - There are getters that return a field's value if set,
- and return the field's default value if unset.
- The getters work even if the receiver is a nil message.
- - The zero value for a struct is its correct initialization state.
- All desired fields must be set before marshaling.
- - A Reset() method will restore a protobuf struct to its zero state.
- - Non-repeated fields are pointers to the values; nil means unset.
- That is, optional or required field int32 f becomes F *int32.
- - Repeated fields are slices.
- - Helper functions are available to aid the setting of fields.
- msg.Foo = proto.String("hello") // set field
- - Constants are defined to hold the default values of all fields that
- have them. They have the form Default_StructName_FieldName.
- Because the getter methods handle defaulted values,
- direct use of these constants should be rare.
- - Enums are given type names and maps from names to values.
- Enum values are prefixed by the enclosing message's name, or by the
- enum's type name if it is a top-level enum. Enum types have a String
- method, and a Enum method to assist in message construction.
- - Nested messages, groups and enums have type names prefixed with the name of
- the surrounding message type.
- - Extensions are given descriptor names that start with E_,
- followed by an underscore-delimited list of the nested messages
- that contain it (if any) followed by the CamelCased name of the
- extension field itself. HasExtension, ClearExtension, GetExtension
- and SetExtension are functions for manipulating extensions.
- - Oneof field sets are given a single field in their message,
- with distinguished wrapper types for each possible field value.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
-When the .proto file specifies `syntax="proto3"`, there are some differences:
-
- - Non-repeated fields of non-message type are values instead of pointers.
- - Enum types do not get an Enum method.
-
-The simplest way to describe this is to see an example.
-Given file test.proto, containing
-
- package example;
-
- enum FOO { X = 17; }
-
- message Test {
- required string label = 1;
- optional int32 type = 2 [default=77];
- repeated int64 reps = 3;
- optional group OptionalGroup = 4 {
- required string RequiredField = 5;
- }
- oneof union {
- int32 number = 6;
- string name = 7;
- }
- }
-
-The resulting file, test.pb.go, is:
-
- package example
-
- import proto "github.com/golang/protobuf/proto"
- import math "math"
-
- type FOO int32
- const (
- FOO_X FOO = 17
- )
- var FOO_name = map[int32]string{
- 17: "X",
- }
- var FOO_value = map[string]int32{
- "X": 17,
- }
-
- func (x FOO) Enum() *FOO {
- p := new(FOO)
- *p = x
- return p
- }
- func (x FOO) String() string {
- return proto.EnumName(FOO_name, int32(x))
- }
- func (x *FOO) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FOO_value, data)
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
- }
-
- type Test struct {
- Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
- Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
- Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
- Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- // Types that are valid to be assigned to Union:
- // *Test_Number
- // *Test_Name
- Union isTest_Union `protobuf_oneof:"union"`
- XXX_unrecognized []byte `json:"-"`
- }
- func (m *Test) Reset() { *m = Test{} }
- func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
-
- type isTest_Union interface {
- isTest_Union()
- }
-
- type Test_Number struct {
- Number int32 `protobuf:"varint,6,opt,name=number"`
- }
- type Test_Name struct {
- Name string `protobuf:"bytes,7,opt,name=name"`
- }
-
- func (*Test_Number) isTest_Union() {}
- func (*Test_Name) isTest_Union() {}
-
- func (m *Test) GetUnion() isTest_Union {
- if m != nil {
- return m.Union
- }
- return nil
- }
- const Default_Test_Type int32 = 77
-
- func (m *Test) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
- }
-
- func (m *Test) GetType() int32 {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return Default_Test_Type
- }
-
- func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
- }
-
- type Test_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
- }
- func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
- func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
-
- func (m *Test_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
- }
-
- func (m *Test) GetNumber() int32 {
- if x, ok := m.GetUnion().(*Test_Number); ok {
- return x.Number
- }
- return 0
- }
-
- func (m *Test) GetName() string {
- if x, ok := m.GetUnion().(*Test_Name); ok {
- return x.Name
- }
- return ""
- }
-
- func init() {
- proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
- }
-
-To create and play with a Test object:
-
- package main
-
- import (
- "log"
-
- "github.com/golang/protobuf/proto"
- pb "./example.pb"
- )
-
- func main() {
- test := &pb.Test{
- Label: proto.String("hello"),
- Type: proto.Int32(17),
- Reps: []int64{1, 2, 3},
- Optionalgroup: &pb.Test_OptionalGroup{
- RequiredField: proto.String("good bye"),
- },
- Union: &pb.Test_Name{"fred"},
- }
- data, err := proto.Marshal(test)
- if err != nil {
- log.Fatal("marshaling error: ", err)
- }
- newTest := &pb.Test{}
- err = proto.Unmarshal(data, newTest)
- if err != nil {
- log.Fatal("unmarshaling error: ", err)
- }
- // Now test and newTest contain the same data.
- if test.GetLabel() != newTest.GetLabel() {
- log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
- }
- // Use a type switch to determine which oneof was set.
- switch u := test.Union.(type) {
- case *pb.Test_Number: // u.Number contains the number.
- case *pb.Test_Name: // u.Name contains the string.
- }
- // etc.
- }
-*/
-package proto
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "reflect"
- "sort"
- "strconv"
- "sync"
-)
-
-// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
-// Marshal reports this when a required field is not initialized.
-// Unmarshal reports this when a required field is missing from the wire data.
-type RequiredNotSetError struct{ field string }
-
-func (e *RequiredNotSetError) Error() string {
- if e.field == "" {
- return fmt.Sprintf("proto: required field not set")
- }
- return fmt.Sprintf("proto: required field %q not set", e.field)
-}
-func (e *RequiredNotSetError) RequiredNotSet() bool {
- return true
-}
-
-type invalidUTF8Error struct{ field string }
-
-func (e *invalidUTF8Error) Error() string {
- if e.field == "" {
- return "proto: invalid UTF-8 detected"
- }
- return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
-}
-func (e *invalidUTF8Error) InvalidUTF8() bool {
- return true
-}
-
-// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
-// This error should not be exposed to the external API as such errors should
-// be recreated with the field information.
-var errInvalidUTF8 = &invalidUTF8Error{}
-
-// isNonFatal reports whether the error is either a RequiredNotSet error
-// or a InvalidUTF8 error.
-func isNonFatal(err error) bool {
- if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
- return true
- }
- if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
- return true
- }
- return false
-}
-
-type nonFatal struct{ E error }
-
-// Merge merges err into nf and reports whether it was successful.
-// Otherwise it returns false for any fatal non-nil errors.
-func (nf *nonFatal) Merge(err error) (ok bool) {
- if err == nil {
- return true // not an error
- }
- if !isNonFatal(err) {
- return false // fatal error
- }
- if nf.E == nil {
- nf.E = err // store first instance of non-fatal error
- }
- return true
-}
-
-// Message is implemented by generated protocol buffer messages.
-type Message interface {
- Reset()
- String() string
- ProtoMessage()
-}
-
-// A Buffer is a buffer manager for marshaling and unmarshaling
-// protocol buffers. It may be reused between invocations to
-// reduce memory usage. It is not necessary to use a Buffer;
-// the global functions Marshal and Unmarshal create a
-// temporary Buffer and are fine for most applications.
-type Buffer struct {
- buf []byte // encode/decode byte stream
- index int // read point
-
- deterministic bool
-}
-
-// NewBuffer allocates a new Buffer and initializes its internal data to
-// the contents of the argument slice.
-func NewBuffer(e []byte) *Buffer {
- return &Buffer{buf: e}
-}
-
-// Reset resets the Buffer, ready for marshaling a new protocol buffer.
-func (p *Buffer) Reset() {
- p.buf = p.buf[0:0] // for reading/writing
- p.index = 0 // for reading
-}
-
-// SetBuf replaces the internal buffer with the slice,
-// ready for unmarshaling the contents of the slice.
-func (p *Buffer) SetBuf(s []byte) {
- p.buf = s
- p.index = 0
-}
-
-// Bytes returns the contents of the Buffer.
-func (p *Buffer) Bytes() []byte { return p.buf }
-
-// SetDeterministic sets whether to use deterministic serialization.
-//
-// Deterministic serialization guarantees that for a given binary, equal
-// messages will always be serialized to the same bytes. This implies:
-//
-// - Repeated serialization of a message will return the same bytes.
-// - Different processes of the same binary (which may be executing on
-// different machines) will serialize equal messages to the same bytes.
-//
-// Note that the deterministic serialization is NOT canonical across
-// languages. It is not guaranteed to remain stable over time. It is unstable
-// across different builds with schema changes due to unknown fields.
-// Users who need canonical serialization (e.g., persistent storage in a
-// canonical form, fingerprinting, etc.) should define their own
-// canonicalization specification and implement their own serializer rather
-// than relying on this API.
-//
-// If deterministic serialization is requested, map entries will be sorted
-// by keys in lexographical order. This is an implementation detail and
-// subject to change.
-func (p *Buffer) SetDeterministic(deterministic bool) {
- p.deterministic = deterministic
-}
-
-/*
- * Helper routines for simplifying the creation of optional fields of basic type.
- */
-
-// Bool is a helper routine that allocates a new bool value
-// to store v and returns a pointer to it.
-func Bool(v bool) *bool {
- return &v
-}
-
-// Int32 is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it.
-func Int32(v int32) *int32 {
- return &v
-}
-
-// Int is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it, but unlike Int32
-// its argument value is an int.
-func Int(v int) *int32 {
- p := new(int32)
- *p = int32(v)
- return p
-}
-
-// Int64 is a helper routine that allocates a new int64 value
-// to store v and returns a pointer to it.
-func Int64(v int64) *int64 {
- return &v
-}
-
-// Float32 is a helper routine that allocates a new float32 value
-// to store v and returns a pointer to it.
-func Float32(v float32) *float32 {
- return &v
-}
-
-// Float64 is a helper routine that allocates a new float64 value
-// to store v and returns a pointer to it.
-func Float64(v float64) *float64 {
- return &v
-}
-
-// Uint32 is a helper routine that allocates a new uint32 value
-// to store v and returns a pointer to it.
-func Uint32(v uint32) *uint32 {
- return &v
-}
-
-// Uint64 is a helper routine that allocates a new uint64 value
-// to store v and returns a pointer to it.
-func Uint64(v uint64) *uint64 {
- return &v
-}
-
-// String is a helper routine that allocates a new string value
-// to store v and returns a pointer to it.
-func String(v string) *string {
- return &v
-}
-
-// EnumName is a helper function to simplify printing protocol buffer enums
-// by name. Given an enum map and a value, it returns a useful string.
-func EnumName(m map[int32]string, v int32) string {
- s, ok := m[v]
- if ok {
- return s
- }
- return strconv.Itoa(int(v))
-}
-
-// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
-// from their JSON-encoded representation. Given a map from the enum's symbolic
-// names to its int values, and a byte buffer containing the JSON-encoded
-// value, it returns an int32 that can be cast to the enum type by the caller.
-//
-// The function can deal with both JSON representations, numeric and symbolic.
-func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
- if data[0] == '"' {
- // New style: enums are strings.
- var repr string
- if err := json.Unmarshal(data, &repr); err != nil {
- return -1, err
- }
- val, ok := m[repr]
- if !ok {
- return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
- }
- return val, nil
- }
- // Old style: enums are ints.
- var val int32
- if err := json.Unmarshal(data, &val); err != nil {
- return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
- }
- return val, nil
-}
-
-// DebugPrint dumps the encoded data in b in a debugging format with a header
-// including the string s. Used in testing but made available for general debugging.
-func (p *Buffer) DebugPrint(s string, b []byte) {
- var u uint64
-
- obuf := p.buf
- index := p.index
- p.buf = b
- p.index = 0
- depth := 0
-
- fmt.Printf("\n--- %s ---\n", s)
-
-out:
- for {
- for i := 0; i < depth; i++ {
- fmt.Print(" ")
- }
-
- index := p.index
- if index == len(p.buf) {
- break
- }
-
- op, err := p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: fetching op err %v\n", index, err)
- break out
- }
- tag := op >> 3
- wire := op & 7
-
- switch wire {
- default:
- fmt.Printf("%3d: t=%3d unknown wire=%d\n",
- index, tag, wire)
- break out
-
- case WireBytes:
- var r []byte
-
- r, err = p.DecodeRawBytes(false)
- if err != nil {
- break out
- }
- fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
- if len(r) <= 6 {
- for i := 0; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- } else {
- for i := 0; i < 3; i++ {
- fmt.Printf(" %.2x", r[i])
- }
- fmt.Printf(" ..")
- for i := len(r) - 3; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- }
- fmt.Printf("\n")
-
- case WireFixed32:
- u, err = p.DecodeFixed32()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
-
- case WireFixed64:
- u, err = p.DecodeFixed64()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
-
- case WireVarint:
- u, err = p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
-
- case WireStartGroup:
- fmt.Printf("%3d: t=%3d start\n", index, tag)
- depth++
-
- case WireEndGroup:
- depth--
- fmt.Printf("%3d: t=%3d end\n", index, tag)
- }
- }
-
- if depth != 0 {
- fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
- }
- fmt.Printf("\n")
-
- p.buf = obuf
- p.index = index
-}
-
-// SetDefaults sets unset protocol buffer fields to their default values.
-// It only modifies fields that are both unset and have defined defaults.
-// It recursively sets default values in any non-nil sub-messages.
-func SetDefaults(pb Message) {
- setDefaults(reflect.ValueOf(pb), true, false)
-}
-
-// v is a pointer to a struct.
-func setDefaults(v reflect.Value, recur, zeros bool) {
- v = v.Elem()
-
- defaultMu.RLock()
- dm, ok := defaults[v.Type()]
- defaultMu.RUnlock()
- if !ok {
- dm = buildDefaultMessage(v.Type())
- defaultMu.Lock()
- defaults[v.Type()] = dm
- defaultMu.Unlock()
- }
-
- for _, sf := range dm.scalars {
- f := v.Field(sf.index)
- if !f.IsNil() {
- // field already set
- continue
- }
- dv := sf.value
- if dv == nil && !zeros {
- // no explicit default, and don't want to set zeros
- continue
- }
- fptr := f.Addr().Interface() // **T
- // TODO: Consider batching the allocations we do here.
- switch sf.kind {
- case reflect.Bool:
- b := new(bool)
- if dv != nil {
- *b = dv.(bool)
- }
- *(fptr.(**bool)) = b
- case reflect.Float32:
- f := new(float32)
- if dv != nil {
- *f = dv.(float32)
- }
- *(fptr.(**float32)) = f
- case reflect.Float64:
- f := new(float64)
- if dv != nil {
- *f = dv.(float64)
- }
- *(fptr.(**float64)) = f
- case reflect.Int32:
- // might be an enum
- if ft := f.Type(); ft != int32PtrType {
- // enum
- f.Set(reflect.New(ft.Elem()))
- if dv != nil {
- f.Elem().SetInt(int64(dv.(int32)))
- }
- } else {
- // int32 field
- i := new(int32)
- if dv != nil {
- *i = dv.(int32)
- }
- *(fptr.(**int32)) = i
- }
- case reflect.Int64:
- i := new(int64)
- if dv != nil {
- *i = dv.(int64)
- }
- *(fptr.(**int64)) = i
- case reflect.String:
- s := new(string)
- if dv != nil {
- *s = dv.(string)
- }
- *(fptr.(**string)) = s
- case reflect.Uint8:
- // exceptional case: []byte
- var b []byte
- if dv != nil {
- db := dv.([]byte)
- b = make([]byte, len(db))
- copy(b, db)
- } else {
- b = []byte{}
- }
- *(fptr.(*[]byte)) = b
- case reflect.Uint32:
- u := new(uint32)
- if dv != nil {
- *u = dv.(uint32)
- }
- *(fptr.(**uint32)) = u
- case reflect.Uint64:
- u := new(uint64)
- if dv != nil {
- *u = dv.(uint64)
- }
- *(fptr.(**uint64)) = u
- default:
- log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
- }
- }
-
- for _, ni := range dm.nested {
- f := v.Field(ni)
- // f is *T or []*T or map[T]*T
- switch f.Kind() {
- case reflect.Ptr:
- if f.IsNil() {
- continue
- }
- setDefaults(f, recur, zeros)
-
- case reflect.Slice:
- for i := 0; i < f.Len(); i++ {
- e := f.Index(i)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
-
- case reflect.Map:
- for _, k := range f.MapKeys() {
- e := f.MapIndex(k)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
- }
- }
-}
-
-var (
- // defaults maps a protocol buffer struct type to a slice of the fields,
- // with its scalar fields set to their proto-declared non-zero default values.
- defaultMu sync.RWMutex
- defaults = make(map[reflect.Type]defaultMessage)
-
- int32PtrType = reflect.TypeOf((*int32)(nil))
-)
-
-// defaultMessage represents information about the default values of a message.
-type defaultMessage struct {
- scalars []scalarField
- nested []int // struct field index of nested messages
-}
-
-type scalarField struct {
- index int // struct field index
- kind reflect.Kind // element type (the T in *T or []T)
- value interface{} // the proto-declared default value, or nil
-}
-
-// t is a struct type.
-func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
- sprop := GetProperties(t)
- for _, prop := range sprop.Prop {
- fi, ok := sprop.decoderTags.get(prop.Tag)
- if !ok {
- // XXX_unrecognized
- continue
- }
- ft := t.Field(fi).Type
-
- sf, nested, err := fieldDefault(ft, prop)
- switch {
- case err != nil:
- log.Print(err)
- case nested:
- dm.nested = append(dm.nested, fi)
- case sf != nil:
- sf.index = fi
- dm.scalars = append(dm.scalars, *sf)
- }
- }
-
- return dm
-}
-
-// fieldDefault returns the scalarField for field type ft.
-// sf will be nil if the field can not have a default.
-// nestedMessage will be true if this is a nested message.
-// Note that sf.index is not set on return.
-func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
- var canHaveDefault bool
- switch ft.Kind() {
- case reflect.Ptr:
- if ft.Elem().Kind() == reflect.Struct {
- nestedMessage = true
- } else {
- canHaveDefault = true // proto2 scalar field
- }
-
- case reflect.Slice:
- switch ft.Elem().Kind() {
- case reflect.Ptr:
- nestedMessage = true // repeated message
- case reflect.Uint8:
- canHaveDefault = true // bytes field
- }
-
- case reflect.Map:
- if ft.Elem().Kind() == reflect.Ptr {
- nestedMessage = true // map with message values
- }
- }
-
- if !canHaveDefault {
- if nestedMessage {
- return nil, true, nil
- }
- return nil, false, nil
- }
-
- // We now know that ft is a pointer or slice.
- sf = &scalarField{kind: ft.Elem().Kind()}
-
- // scalar fields without defaults
- if !prop.HasDefault {
- return sf, false, nil
- }
-
- // a scalar field: either *T or []byte
- switch ft.Elem().Kind() {
- case reflect.Bool:
- x, err := strconv.ParseBool(prop.Default)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Float32:
- x, err := strconv.ParseFloat(prop.Default, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
- }
- sf.value = float32(x)
- case reflect.Float64:
- x, err := strconv.ParseFloat(prop.Default, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Int32:
- x, err := strconv.ParseInt(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
- }
- sf.value = int32(x)
- case reflect.Int64:
- x, err := strconv.ParseInt(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.String:
- sf.value = prop.Default
- case reflect.Uint8:
- // []byte (not *uint8)
- sf.value = []byte(prop.Default)
- case reflect.Uint32:
- x, err := strconv.ParseUint(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
- }
- sf.value = uint32(x)
- case reflect.Uint64:
- x, err := strconv.ParseUint(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
- }
- sf.value = x
- default:
- return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
- }
-
- return sf, false, nil
-}
-
-// mapKeys returns a sort.Interface to be used for sorting the map keys.
-// Map fields may have key types of non-float scalars, strings and enums.
-func mapKeys(vs []reflect.Value) sort.Interface {
- s := mapKeySorter{vs: vs}
-
- // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
- if len(vs) == 0 {
- return s
- }
- switch vs[0].Kind() {
- case reflect.Int32, reflect.Int64:
- s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
- case reflect.Uint32, reflect.Uint64:
- s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
- case reflect.Bool:
- s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
- case reflect.String:
- s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
- default:
- panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
- }
-
- return s
-}
-
-type mapKeySorter struct {
- vs []reflect.Value
- less func(a, b reflect.Value) bool
-}
-
-func (s mapKeySorter) Len() int { return len(s.vs) }
-func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
-func (s mapKeySorter) Less(i, j int) bool {
- return s.less(s.vs[i], s.vs[j])
-}
-
-// isProto3Zero reports whether v is a zero proto3 value.
-func isProto3Zero(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint32, reflect.Uint64:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.String:
- return v.String() == ""
- }
- return false
-}
-
-const (
- // ProtoPackageIsVersion3 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion3 = true
-
- // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion2 = true
-
- // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion1 = true
-)
-
-// InternalMessageInfo is a type used internally by generated .pb.go files.
-// This type is not intended to be used by non-generated code.
-// This type is not subject to any compatibility guarantee.
-type InternalMessageInfo struct {
- marshal *marshalInfo
- unmarshal *unmarshalInfo
- merge *mergeInfo
- discard *discardInfo
-}
diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go
deleted file mode 100644
index f48a756..0000000
--- a/vendor/github.com/golang/protobuf/proto/message_set.go
+++ /dev/null
@@ -1,181 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-/*
- * Support for message sets.
- */
-
-import (
- "errors"
-)
-
-// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
-// A message type ID is required for storing a protocol buffer in a message set.
-var errNoMessageTypeID = errors.New("proto does not have a message type ID")
-
-// The first two types (_MessageSet_Item and messageSet)
-// model what the protocol compiler produces for the following protocol message:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-// That is the MessageSet wire format. We can't use a proto to generate these
-// because that would introduce a circular dependency between it and this package.
-
-type _MessageSet_Item struct {
- TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
- Message []byte `protobuf:"bytes,3,req,name=message"`
-}
-
-type messageSet struct {
- Item []*_MessageSet_Item `protobuf:"group,1,rep"`
- XXX_unrecognized []byte
- // TODO: caching?
-}
-
-// Make sure messageSet is a Message.
-var _ Message = (*messageSet)(nil)
-
-// messageTypeIder is an interface satisfied by a protocol buffer type
-// that may be stored in a MessageSet.
-type messageTypeIder interface {
- MessageTypeId() int32
-}
-
-func (ms *messageSet) find(pb Message) *_MessageSet_Item {
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return nil
- }
- id := mti.MessageTypeId()
- for _, item := range ms.Item {
- if *item.TypeId == id {
- return item
- }
- }
- return nil
-}
-
-func (ms *messageSet) Has(pb Message) bool {
- return ms.find(pb) != nil
-}
-
-func (ms *messageSet) Unmarshal(pb Message) error {
- if item := ms.find(pb); item != nil {
- return Unmarshal(item.Message, pb)
- }
- if _, ok := pb.(messageTypeIder); !ok {
- return errNoMessageTypeID
- }
- return nil // TODO: return error instead?
-}
-
-func (ms *messageSet) Marshal(pb Message) error {
- msg, err := Marshal(pb)
- if err != nil {
- return err
- }
- if item := ms.find(pb); item != nil {
- // reuse existing item
- item.Message = msg
- return nil
- }
-
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return errNoMessageTypeID
- }
-
- mtid := mti.MessageTypeId()
- ms.Item = append(ms.Item, &_MessageSet_Item{
- TypeId: &mtid,
- Message: msg,
- })
- return nil
-}
-
-func (ms *messageSet) Reset() { *ms = messageSet{} }
-func (ms *messageSet) String() string { return CompactTextString(ms) }
-func (*messageSet) ProtoMessage() {}
-
-// Support for the message_set_wire_format message option.
-
-func skipVarint(buf []byte) []byte {
- i := 0
- for ; buf[i]&0x80 != 0; i++ {
- }
- return buf[i+1:]
-}
-
-// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
-// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
-func unmarshalMessageSet(buf []byte, exts interface{}) error {
- var m map[int32]Extension
- switch exts := exts.(type) {
- case *XXX_InternalExtensions:
- m = exts.extensionsWrite()
- case map[int32]Extension:
- m = exts
- default:
- return errors.New("proto: not an extension map")
- }
-
- ms := new(messageSet)
- if err := Unmarshal(buf, ms); err != nil {
- return err
- }
- for _, item := range ms.Item {
- id := *item.TypeId
- msg := item.Message
-
- // Restore wire type and field number varint, plus length varint.
- // Be careful to preserve duplicate items.
- b := EncodeVarint(uint64(id)<<3 | WireBytes)
- if ext, ok := m[id]; ok {
- // Existing data; rip off the tag and length varint
- // so we join the new data correctly.
- // We can assume that ext.enc is set because we are unmarshaling.
- o := ext.enc[len(b):] // skip wire type and field number
- _, n := DecodeVarint(o) // calculate length of length varint
- o = o[n:] // skip length varint
- msg = append(o, msg...) // join old data and new data
- }
- b = append(b, EncodeVarint(uint64(len(msg)))...)
- b = append(b, msg...)
-
- m[id] = Extension{enc: b}
- }
- return nil
-}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
deleted file mode 100644
index 94fa919..0000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
+++ /dev/null
@@ -1,360 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-// +build purego appengine js
-
-// This file contains an implementation of proto field accesses using package reflect.
-// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
-// be used on App Engine.
-
-package proto
-
-import (
- "reflect"
- "sync"
-)
-
-const unsafeAllowed = false
-
-// A field identifies a field in a struct, accessible from a pointer.
-// In this implementation, a field is identified by the sequence of field indices
-// passed to reflect's FieldByIndex.
-type field []int
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return f.Index
-}
-
-// invalidField is an invalid field identifier.
-var invalidField = field(nil)
-
-// zeroField is a noop when calling pointer.offset.
-var zeroField = field([]int{})
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool { return f != nil }
-
-// The pointer type is for the table-driven decoder.
-// The implementation here uses a reflect.Value of pointer type to
-// create a generic pointer. In pointer_unsafe.go we use unsafe
-// instead of reflect to implement the same (but faster) interface.
-type pointer struct {
- v reflect.Value
-}
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- return pointer{v: reflect.ValueOf(*i)}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr, deref bool) pointer {
- v := reflect.ValueOf(*i)
- u := reflect.New(v.Type())
- u.Elem().Set(v)
- if deref {
- u = u.Elem()
- }
- return pointer{v: u}
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{v: v}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
-}
-
-func (p pointer) isNil() bool {
- return p.v.IsNil()
-}
-
-// grow updates the slice s in place to make it one element longer.
-// s must be addressable.
-// Returns the (addressable) new element.
-func grow(s reflect.Value) reflect.Value {
- n, m := s.Len(), s.Cap()
- if n < m {
- s.SetLen(n + 1)
- } else {
- s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
- }
- return s.Index(n)
-}
-
-func (p pointer) toInt64() *int64 {
- return p.v.Interface().(*int64)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return p.v.Interface().(**int64)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return p.v.Interface().(*[]int64)
-}
-
-var int32ptr = reflect.TypeOf((*int32)(nil))
-
-func (p pointer) toInt32() *int32 {
- return p.v.Convert(int32ptr).Interface().(*int32)
-}
-
-// The toInt32Ptr/Slice methods don't work because of enums.
-// Instead, we must use set/get methods for the int32ptr/slice case.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return p.v.Interface().(**int32)
-}
- func (p pointer) toInt32Slice() *[]int32 {
- return p.v.Interface().(*[]int32)
-}
-*/
-func (p pointer) getInt32Ptr() *int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().(*int32)
- }
- // an enum
- return p.v.Elem().Convert(int32PtrType).Interface().(*int32)
-}
-func (p pointer) setInt32Ptr(v int32) {
- // Allocate value in a *int32. Possibly convert that to a *enum.
- // Then assign it to a **int32 or **enum.
- // Note: we can convert *int32 to *enum, but we can't convert
- // **int32 to **enum!
- p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem()))
-}
-
-// getInt32Slice copies []int32 from p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getInt32Slice() []int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().([]int32)
- }
- // an enum
- // Allocate a []int32, then assign []enum's values into it.
- // Note: we can't convert []enum to []int32.
- slice := p.v.Elem()
- s := make([]int32, slice.Len())
- for i := 0; i < slice.Len(); i++ {
- s[i] = int32(slice.Index(i).Int())
- }
- return s
-}
-
-// setInt32Slice copies []int32 into p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setInt32Slice(v []int32) {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- p.v.Elem().Set(reflect.ValueOf(v))
- return
- }
- // an enum
- // Allocate a []enum, then assign []int32's values into it.
- // Note: we can't convert []enum to []int32.
- slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
- for i, x := range v {
- slice.Index(i).SetInt(int64(x))
- }
- p.v.Elem().Set(slice)
-}
-func (p pointer) appendInt32Slice(v int32) {
- grow(p.v.Elem()).SetInt(int64(v))
-}
-
-func (p pointer) toUint64() *uint64 {
- return p.v.Interface().(*uint64)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return p.v.Interface().(**uint64)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return p.v.Interface().(*[]uint64)
-}
-func (p pointer) toUint32() *uint32 {
- return p.v.Interface().(*uint32)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return p.v.Interface().(**uint32)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return p.v.Interface().(*[]uint32)
-}
-func (p pointer) toBool() *bool {
- return p.v.Interface().(*bool)
-}
-func (p pointer) toBoolPtr() **bool {
- return p.v.Interface().(**bool)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return p.v.Interface().(*[]bool)
-}
-func (p pointer) toFloat64() *float64 {
- return p.v.Interface().(*float64)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return p.v.Interface().(**float64)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return p.v.Interface().(*[]float64)
-}
-func (p pointer) toFloat32() *float32 {
- return p.v.Interface().(*float32)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return p.v.Interface().(**float32)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return p.v.Interface().(*[]float32)
-}
-func (p pointer) toString() *string {
- return p.v.Interface().(*string)
-}
-func (p pointer) toStringPtr() **string {
- return p.v.Interface().(**string)
-}
-func (p pointer) toStringSlice() *[]string {
- return p.v.Interface().(*[]string)
-}
-func (p pointer) toBytes() *[]byte {
- return p.v.Interface().(*[]byte)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return p.v.Interface().(*[][]byte)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return p.v.Interface().(*XXX_InternalExtensions)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return p.v.Interface().(*map[int32]Extension)
-}
-func (p pointer) getPointer() pointer {
- return pointer{v: p.v.Elem()}
-}
-func (p pointer) setPointer(q pointer) {
- p.v.Elem().Set(q.v)
-}
-func (p pointer) appendPointer(q pointer) {
- grow(p.v.Elem()).Set(q.v)
-}
-
-// getPointerSlice copies []*T from p as a new []pointer.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getPointerSlice() []pointer {
- if p.v.IsNil() {
- return nil
- }
- n := p.v.Elem().Len()
- s := make([]pointer, n)
- for i := 0; i < n; i++ {
- s[i] = pointer{v: p.v.Elem().Index(i)}
- }
- return s
-}
-
-// setPointerSlice copies []pointer into p as a new []*T.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setPointerSlice(v []pointer) {
- if v == nil {
- p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
- return
- }
- s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
- for _, p := range v {
- s = reflect.Append(s, p.v)
- }
- p.v.Elem().Set(s)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- if p.v.Elem().IsNil() {
- return pointer{v: p.v.Elem()}
- }
- return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
-}
-
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- // TODO: check that p.v.Type().Elem() == t?
- return p.v
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-
-var atomicLock sync.Mutex
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
deleted file mode 100644
index dbfffe0..0000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ /dev/null
@@ -1,313 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-// +build !purego,!appengine,!js
-
-// This file contains the implementation of the proto field accesses using package unsafe.
-
-package proto
-
-import (
- "reflect"
- "sync/atomic"
- "unsafe"
-)
-
-const unsafeAllowed = true
-
-// A field identifies a field in a struct, accessible from a pointer.
-// In this implementation, a field is identified by its byte offset from the start of the struct.
-type field uintptr
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return field(f.Offset)
-}
-
-// invalidField is an invalid field identifier.
-const invalidField = ^field(0)
-
-// zeroField is a noop when calling pointer.offset.
-const zeroField = field(0)
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool {
- return f != invalidField
-}
-
-// The pointer type below is for the new table-driven encoder/decoder.
-// The implementation here uses unsafe.Pointer to create a generic pointer.
-// In pointer_reflect.go we use reflect instead of unsafe to implement
-// the same (but slower) interface.
-type pointer struct {
- p unsafe.Pointer
-}
-
-// size of pointer
-var ptrSize = unsafe.Sizeof(uintptr(0))
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- // Super-tricky - read pointer out of data word of interface value.
- // Saves ~25ns over the equivalent:
- // return valToPointer(reflect.ValueOf(*i))
- return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr, deref bool) (p pointer) {
- // Super-tricky - read or get the address of data word of interface value.
- if isptr {
- // The interface is of pointer type, thus it is a direct interface.
- // The data word is the pointer data itself. We take its address.
- p = pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)}
- } else {
- // The interface is not of pointer type. The data word is the pointer
- // to the data.
- p = pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
- }
- if deref {
- p.p = *(*unsafe.Pointer)(p.p)
- }
- return p
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{p: unsafe.Pointer(v.Pointer())}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- // For safety, we should panic if !f.IsValid, however calling panic causes
- // this to no longer be inlineable, which is a serious performance cost.
- /*
- if !f.IsValid() {
- panic("invalid field")
- }
- */
- return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))}
-}
-
-func (p pointer) isNil() bool {
- return p.p == nil
-}
-
-func (p pointer) toInt64() *int64 {
- return (*int64)(p.p)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return (**int64)(p.p)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return (*[]int64)(p.p)
-}
-func (p pointer) toInt32() *int32 {
- return (*int32)(p.p)
-}
-
-// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return (**int32)(p.p)
- }
- func (p pointer) toInt32Slice() *[]int32 {
- return (*[]int32)(p.p)
- }
-*/
-func (p pointer) getInt32Ptr() *int32 {
- return *(**int32)(p.p)
-}
-func (p pointer) setInt32Ptr(v int32) {
- *(**int32)(p.p) = &v
-}
-
-// getInt32Slice loads a []int32 from p.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getInt32Slice() []int32 {
- return *(*[]int32)(p.p)
-}
-
-// setInt32Slice stores a []int32 to p.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setInt32Slice(v []int32) {
- *(*[]int32)(p.p) = v
-}
-
-// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead?
-func (p pointer) appendInt32Slice(v int32) {
- s := (*[]int32)(p.p)
- *s = append(*s, v)
-}
-
-func (p pointer) toUint64() *uint64 {
- return (*uint64)(p.p)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return (**uint64)(p.p)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return (*[]uint64)(p.p)
-}
-func (p pointer) toUint32() *uint32 {
- return (*uint32)(p.p)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return (**uint32)(p.p)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return (*[]uint32)(p.p)
-}
-func (p pointer) toBool() *bool {
- return (*bool)(p.p)
-}
-func (p pointer) toBoolPtr() **bool {
- return (**bool)(p.p)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return (*[]bool)(p.p)
-}
-func (p pointer) toFloat64() *float64 {
- return (*float64)(p.p)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return (**float64)(p.p)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return (*[]float64)(p.p)
-}
-func (p pointer) toFloat32() *float32 {
- return (*float32)(p.p)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return (**float32)(p.p)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return (*[]float32)(p.p)
-}
-func (p pointer) toString() *string {
- return (*string)(p.p)
-}
-func (p pointer) toStringPtr() **string {
- return (**string)(p.p)
-}
-func (p pointer) toStringSlice() *[]string {
- return (*[]string)(p.p)
-}
-func (p pointer) toBytes() *[]byte {
- return (*[]byte)(p.p)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return (*[][]byte)(p.p)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return (*XXX_InternalExtensions)(p.p)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return (*map[int32]Extension)(p.p)
-}
-
-// getPointerSlice loads []*T from p as a []pointer.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getPointerSlice() []pointer {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We load it as []pointer.
- return *(*[]pointer)(p.p)
-}
-
-// setPointerSlice stores []pointer into p as a []*T.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setPointerSlice(v []pointer) {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We store it as []pointer.
- *(*[]pointer)(p.p) = v
-}
-
-// getPointer loads the pointer at p and returns it.
-func (p pointer) getPointer() pointer {
- return pointer{p: *(*unsafe.Pointer)(p.p)}
-}
-
-// setPointer stores the pointer q at p.
-func (p pointer) setPointer(q pointer) {
- *(*unsafe.Pointer)(p.p) = q.p
-}
-
-// append q to the slice pointed to by p.
-func (p pointer) appendPointer(q pointer) {
- s := (*[]unsafe.Pointer)(p.p)
- *s = append(*s, q.p)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- // Super-tricky - read pointer out of data word of interface value.
- return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]}
-}
-
-// asPointerTo returns a reflect.Value that is a pointer to an
-// object of type t stored at p.
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- return reflect.NewAt(t, p.p)
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go
deleted file mode 100644
index 79668ff..0000000
--- a/vendor/github.com/golang/protobuf/proto/properties.go
+++ /dev/null
@@ -1,545 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
-import (
- "fmt"
- "log"
- "os"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "sync"
-)
-
-const debug bool = false
-
-// Constants that identify the encoding of a value on the wire.
-const (
- WireVarint = 0
- WireFixed64 = 1
- WireBytes = 2
- WireStartGroup = 3
- WireEndGroup = 4
- WireFixed32 = 5
-)
-
-// tagMap is an optimization over map[int]int for typical protocol buffer
-// use-cases. Encoded protocol buffers are often in tag order with small tag
-// numbers.
-type tagMap struct {
- fastTags []int
- slowTags map[int]int
-}
-
-// tagMapFastLimit is the upper bound on the tag number that will be stored in
-// the tagMap slice rather than its map.
-const tagMapFastLimit = 1024
-
-func (p *tagMap) get(t int) (int, bool) {
- if t > 0 && t < tagMapFastLimit {
- if t >= len(p.fastTags) {
- return 0, false
- }
- fi := p.fastTags[t]
- return fi, fi >= 0
- }
- fi, ok := p.slowTags[t]
- return fi, ok
-}
-
-func (p *tagMap) put(t int, fi int) {
- if t > 0 && t < tagMapFastLimit {
- for len(p.fastTags) < t+1 {
- p.fastTags = append(p.fastTags, -1)
- }
- p.fastTags[t] = fi
- return
- }
- if p.slowTags == nil {
- p.slowTags = make(map[int]int)
- }
- p.slowTags[t] = fi
-}
-
-// StructProperties represents properties for all the fields of a struct.
-// decoderTags and decoderOrigNames should only be used by the decoder.
-type StructProperties struct {
- Prop []*Properties // properties for each field
- reqCount int // required count
- decoderTags tagMap // map from proto tag to struct field number
- decoderOrigNames map[string]int // map from original name to struct field number
- order []int // list of struct field numbers in tag order
-
- // OneofTypes contains information about the oneof fields in this message.
- // It is keyed by the original name of a field.
- OneofTypes map[string]*OneofProperties
-}
-
-// OneofProperties represents information about a specific field in a oneof.
-type OneofProperties struct {
- Type reflect.Type // pointer to generated struct type for this oneof field
- Field int // struct field number of the containing oneof in the message
- Prop *Properties
-}
-
-// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
-// See encode.go, (*Buffer).enc_struct.
-
-func (sp *StructProperties) Len() int { return len(sp.order) }
-func (sp *StructProperties) Less(i, j int) bool {
- return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
-}
-func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
-
-// Properties represents the protocol-specific behavior of a single struct field.
-type Properties struct {
- Name string // name of the field, for error messages
- OrigName string // original name before protocol compiler (always set)
- JSONName string // name to use for JSON; determined by protoc
- Wire string
- WireType int
- Tag int
- Required bool
- Optional bool
- Repeated bool
- Packed bool // relevant for repeated primitives only
- Enum string // set for enum types only
- proto3 bool // whether this is known to be a proto3 field
- oneof bool // whether this is a oneof field
-
- Default string // default value
- HasDefault bool // whether an explicit default was provided
-
- stype reflect.Type // set for struct types only
- sprop *StructProperties // set for struct types only
-
- mtype reflect.Type // set for map types only
- MapKeyProp *Properties // set for map types only
- MapValProp *Properties // set for map types only
-}
-
-// String formats the properties in the protobuf struct field tag style.
-func (p *Properties) String() string {
- s := p.Wire
- s += ","
- s += strconv.Itoa(p.Tag)
- if p.Required {
- s += ",req"
- }
- if p.Optional {
- s += ",opt"
- }
- if p.Repeated {
- s += ",rep"
- }
- if p.Packed {
- s += ",packed"
- }
- s += ",name=" + p.OrigName
- if p.JSONName != p.OrigName {
- s += ",json=" + p.JSONName
- }
- if p.proto3 {
- s += ",proto3"
- }
- if p.oneof {
- s += ",oneof"
- }
- if len(p.Enum) > 0 {
- s += ",enum=" + p.Enum
- }
- if p.HasDefault {
- s += ",def=" + p.Default
- }
- return s
-}
-
-// Parse populates p by parsing a string in the protobuf struct field tag style.
-func (p *Properties) Parse(s string) {
- // "bytes,49,opt,name=foo,def=hello!"
- fields := strings.Split(s, ",") // breaks def=, but handled below.
- if len(fields) < 2 {
- fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
- return
- }
-
- p.Wire = fields[0]
- switch p.Wire {
- case "varint":
- p.WireType = WireVarint
- case "fixed32":
- p.WireType = WireFixed32
- case "fixed64":
- p.WireType = WireFixed64
- case "zigzag32":
- p.WireType = WireVarint
- case "zigzag64":
- p.WireType = WireVarint
- case "bytes", "group":
- p.WireType = WireBytes
- // no numeric converter for non-numeric types
- default:
- fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
- return
- }
-
- var err error
- p.Tag, err = strconv.Atoi(fields[1])
- if err != nil {
- return
- }
-
-outer:
- for i := 2; i < len(fields); i++ {
- f := fields[i]
- switch {
- case f == "req":
- p.Required = true
- case f == "opt":
- p.Optional = true
- case f == "rep":
- p.Repeated = true
- case f == "packed":
- p.Packed = true
- case strings.HasPrefix(f, "name="):
- p.OrigName = f[5:]
- case strings.HasPrefix(f, "json="):
- p.JSONName = f[5:]
- case strings.HasPrefix(f, "enum="):
- p.Enum = f[5:]
- case f == "proto3":
- p.proto3 = true
- case f == "oneof":
- p.oneof = true
- case strings.HasPrefix(f, "def="):
- p.HasDefault = true
- p.Default = f[4:] // rest of string
- if i+1 < len(fields) {
- // Commas aren't escaped, and def is always last.
- p.Default += "," + strings.Join(fields[i+1:], ",")
- break outer
- }
- }
- }
-}
-
-var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
-
-// setFieldProps initializes the field properties for submessages and maps.
-func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
- switch t1 := typ; t1.Kind() {
- case reflect.Ptr:
- if t1.Elem().Kind() == reflect.Struct {
- p.stype = t1.Elem()
- }
-
- case reflect.Slice:
- if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct {
- p.stype = t2.Elem()
- }
-
- case reflect.Map:
- p.mtype = t1
- p.MapKeyProp = &Properties{}
- p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
- p.MapValProp = &Properties{}
- vtype := p.mtype.Elem()
- if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
- // The value type is not a message (*T) or bytes ([]byte),
- // so we need encoders for the pointer to this type.
- vtype = reflect.PtrTo(vtype)
- }
- p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
- }
-
- if p.stype != nil {
- if lockGetProp {
- p.sprop = GetProperties(p.stype)
- } else {
- p.sprop = getPropertiesLocked(p.stype)
- }
- }
-}
-
-var (
- marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
-)
-
-// Init populates the properties from a protocol buffer struct tag.
-func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
- p.init(typ, name, tag, f, true)
-}
-
-func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
- // "bytes,49,opt,def=hello!"
- p.Name = name
- p.OrigName = name
- if tag == "" {
- return
- }
- p.Parse(tag)
- p.setFieldProps(typ, f, lockGetProp)
-}
-
-var (
- propertiesMu sync.RWMutex
- propertiesMap = make(map[reflect.Type]*StructProperties)
-)
-
-// GetProperties returns the list of properties for the type represented by t.
-// t must represent a generated struct type of a protocol message.
-func GetProperties(t reflect.Type) *StructProperties {
- if t.Kind() != reflect.Struct {
- panic("proto: type must have kind struct")
- }
-
- // Most calls to GetProperties in a long-running program will be
- // retrieving details for types we have seen before.
- propertiesMu.RLock()
- sprop, ok := propertiesMap[t]
- propertiesMu.RUnlock()
- if ok {
- return sprop
- }
-
- propertiesMu.Lock()
- sprop = getPropertiesLocked(t)
- propertiesMu.Unlock()
- return sprop
-}
-
-type (
- oneofFuncsIface interface {
- XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
- }
- oneofWrappersIface interface {
- XXX_OneofWrappers() []interface{}
- }
-)
-
-// getPropertiesLocked requires that propertiesMu is held.
-func getPropertiesLocked(t reflect.Type) *StructProperties {
- if prop, ok := propertiesMap[t]; ok {
- return prop
- }
-
- prop := new(StructProperties)
- // in case of recursive protos, fill this in now.
- propertiesMap[t] = prop
-
- // build properties
- prop.Prop = make([]*Properties, t.NumField())
- prop.order = make([]int, t.NumField())
-
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- p := new(Properties)
- name := f.Name
- p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
-
- oneof := f.Tag.Get("protobuf_oneof") // special case
- if oneof != "" {
- // Oneof fields don't use the traditional protobuf tag.
- p.OrigName = oneof
- }
- prop.Prop[i] = p
- prop.order[i] = i
- if debug {
- print(i, " ", f.Name, " ", t.String(), " ")
- if p.Tag > 0 {
- print(p.String())
- }
- print("\n")
- }
- }
-
- // Re-order prop.order.
- sort.Sort(prop)
-
- var oots []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oots = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oots = m.XXX_OneofWrappers()
- }
- if len(oots) > 0 {
- // Interpret oneof metadata.
- prop.OneofTypes = make(map[string]*OneofProperties)
- for _, oot := range oots {
- oop := &OneofProperties{
- Type: reflect.ValueOf(oot).Type(), // *T
- Prop: new(Properties),
- }
- sft := oop.Type.Elem().Field(0)
- oop.Prop.Name = sft.Name
- oop.Prop.Parse(sft.Tag.Get("protobuf"))
- // There will be exactly one interface field that
- // this new value is assignable to.
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if f.Type.Kind() != reflect.Interface {
- continue
- }
- if !oop.Type.AssignableTo(f.Type) {
- continue
- }
- oop.Field = i
- break
- }
- prop.OneofTypes[oop.Prop.OrigName] = oop
- }
- }
-
- // build required counts
- // build tags
- reqCount := 0
- prop.decoderOrigNames = make(map[string]int)
- for i, p := range prop.Prop {
- if strings.HasPrefix(p.Name, "XXX_") {
- // Internal fields should not appear in tags/origNames maps.
- // They are handled specially when encoding and decoding.
- continue
- }
- if p.Required {
- reqCount++
- }
- prop.decoderTags.put(p.Tag, i)
- prop.decoderOrigNames[p.OrigName] = i
- }
- prop.reqCount = reqCount
-
- return prop
-}
-
-// A global registry of enum types.
-// The generated code will register the generated maps by calling RegisterEnum.
-
-var enumValueMaps = make(map[string]map[string]int32)
-
-// RegisterEnum is called from the generated code to install the enum descriptor
-// maps into the global table to aid parsing text format protocol buffers.
-func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
- if _, ok := enumValueMaps[typeName]; ok {
- panic("proto: duplicate enum registered: " + typeName)
- }
- enumValueMaps[typeName] = valueMap
-}
-
-// EnumValueMap returns the mapping from names to integers of the
-// enum type enumType, or a nil if not found.
-func EnumValueMap(enumType string) map[string]int32 {
- return enumValueMaps[enumType]
-}
-
-// A registry of all linked message types.
-// The string is a fully-qualified proto name ("pkg.Message").
-var (
- protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers
- protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types
- revProtoTypes = make(map[reflect.Type]string)
-)
-
-// RegisterType is called from generated code and maps from the fully qualified
-// proto name to the type (pointer to struct) of the protocol buffer.
-func RegisterType(x Message, name string) {
- if _, ok := protoTypedNils[name]; ok {
- // TODO: Some day, make this a panic.
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
- // Generated code always calls RegisterType with nil x.
- // This check is just for extra safety.
- protoTypedNils[name] = x
- } else {
- protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
- }
- revProtoTypes[t] = name
-}
-
-// RegisterMapType is called from generated code and maps from the fully qualified
-// proto name to the native map type of the proto map definition.
-func RegisterMapType(x interface{}, name string) {
- if reflect.TypeOf(x).Kind() != reflect.Map {
- panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
- }
- if _, ok := protoMapTypes[name]; ok {
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- protoMapTypes[name] = t
- revProtoTypes[t] = name
-}
-
-// MessageName returns the fully-qualified proto name for the given message type.
-func MessageName(x Message) string {
- type xname interface {
- XXX_MessageName() string
- }
- if m, ok := x.(xname); ok {
- return m.XXX_MessageName()
- }
- return revProtoTypes[reflect.TypeOf(x)]
-}
-
-// MessageType returns the message type (pointer to struct) for a named message.
-// The type is not guaranteed to implement proto.Message if the name refers to a
-// map entry.
-func MessageType(name string) reflect.Type {
- if t, ok := protoTypedNils[name]; ok {
- return reflect.TypeOf(t)
- }
- return protoMapTypes[name]
-}
-
-// A registry of all linked proto files.
-var (
- protoFiles = make(map[string][]byte) // file name => fileDescriptor
-)
-
-// RegisterFile is called from generated code and maps from the
-// full file name of a .proto file to its compressed FileDescriptorProto.
-func RegisterFile(filename string, fileDescriptor []byte) {
- protoFiles[filename] = fileDescriptor
-}
-
-// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
-func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go
deleted file mode 100644
index 5cb11fa..0000000
--- a/vendor/github.com/golang/protobuf/proto/table_marshal.go
+++ /dev/null
@@ -1,2776 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-import (
- "errors"
- "fmt"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// a sizer takes a pointer to a field and the size of its tag, computes the size of
-// the encoded data.
-type sizer func(pointer, int) int
-
-// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
-// marshals the field to the end of the slice, returns the slice and error (if any).
-type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
-
-// marshalInfo is the information used for marshaling a message.
-type marshalInfo struct {
- typ reflect.Type
- fields []*marshalFieldInfo
- unrecognized field // offset of XXX_unrecognized
- extensions field // offset of XXX_InternalExtensions
- v1extensions field // offset of XXX_extensions
- sizecache field // offset of XXX_sizecache
- initialized int32 // 0 -- only typ is set, 1 -- fully initialized
- messageset bool // uses message set wire format
- hasmarshaler bool // has custom marshaler
- sync.RWMutex // protect extElems map, also for initialization
- extElems map[int32]*marshalElemInfo // info of extension elements
-}
-
-// marshalFieldInfo is the information used for marshaling a field of a message.
-type marshalFieldInfo struct {
- field field
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isPointer bool
- required bool // field is required
- name string // name of the field, for error reporting
- oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
-}
-
-// marshalElemInfo is the information used for marshaling an extension or oneof element.
-type marshalElemInfo struct {
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
- deref bool // dereference the pointer before operating on it; implies isptr
-}
-
-var (
- marshalInfoMap = map[reflect.Type]*marshalInfo{}
- marshalInfoLock sync.Mutex
-)
-
-// getMarshalInfo returns the information to marshal a given type of message.
-// The info it returns may not necessarily initialized.
-// t is the type of the message (NOT the pointer to it).
-func getMarshalInfo(t reflect.Type) *marshalInfo {
- marshalInfoLock.Lock()
- u, ok := marshalInfoMap[t]
- if !ok {
- u = &marshalInfo{typ: t}
- marshalInfoMap[t] = u
- }
- marshalInfoLock.Unlock()
- return u
-}
-
-// Size is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It computes the size of encoded data of msg.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Size(msg Message) int {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return 0
- }
- return u.size(ptr)
-}
-
-// Marshal is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It marshals msg to the end of b.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return b, ErrNil
- }
- return u.marshal(b, ptr, deterministic)
-}
-
-func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
- // u := a.marshal, but atomically.
- // We use an atomic here to ensure memory consistency.
- u := atomicLoadMarshalInfo(&a.marshal)
- if u == nil {
- // Get marshal information from type of message.
- t := reflect.ValueOf(msg).Type()
- if t.Kind() != reflect.Ptr {
- panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
- }
- u = getMarshalInfo(t.Elem())
- // Store it in the cache for later users.
- // a.marshal = u, but atomically.
- atomicStoreMarshalInfo(&a.marshal, u)
- }
- return u
-}
-
-// size is the main function to compute the size of the encoded data of a message.
-// ptr is the pointer to the message.
-func (u *marshalInfo) size(ptr pointer) int {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b, _ := m.Marshal()
- return len(b)
- }
-
- n := 0
- for _, f := range u.fields {
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- n += f.sizer(ptr.offset(f.field), f.tagsize)
- }
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- n += u.sizeMessageSet(e)
- } else {
- n += u.sizeExtensions(e)
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- n += u.sizeV1Extensions(m)
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- n += len(s)
- }
- // cache the result for use in marshal
- if u.sizecache.IsValid() {
- atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
- }
- return n
-}
-
-// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
-// fall back to compute the size.
-func (u *marshalInfo) cachedsize(ptr pointer) int {
- if u.sizecache.IsValid() {
- return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
- }
- return u.size(ptr)
-}
-
-// marshal is the main function to marshal a message. It takes a byte slice and appends
-// the encoded data to the end of the slice, returns the slice and error (if any).
-// ptr is the pointer to the message.
-// If deterministic is true, map is marshaled in deterministic order.
-func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b1, err := m.Marshal()
- b = append(b, b1...)
- return b, err
- }
-
- var err, errLater error
- // The old marshaler encodes extensions at beginning.
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- b, err = u.appendMessageSet(b, e, deterministic)
- } else {
- b, err = u.appendExtensions(b, e, deterministic)
- }
- if err != nil {
- return b, err
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- b, err = u.appendV1Extensions(b, m, deterministic)
- if err != nil {
- return b, err
- }
- }
- for _, f := range u.fields {
- if f.required {
- if ptr.offset(f.field).getPointer().isNil() {
- // Required field is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errLater == nil {
- errLater = &RequiredNotSetError{f.name}
- }
- continue
- }
- }
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
- if err != nil {
- if err1, ok := err.(*RequiredNotSetError); ok {
- // Required field in submessage is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errLater == nil {
- errLater = &RequiredNotSetError{f.name + "." + err1.field}
- }
- continue
- }
- if err == errRepeatedHasNil {
- err = errors.New("proto: repeated field " + f.name + " has nil element")
- }
- if err == errInvalidUTF8 {
- if errLater == nil {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- errLater = &invalidUTF8Error{fullName}
- }
- continue
- }
- return b, err
- }
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- b = append(b, s...)
- }
- return b, errLater
-}
-
-// computeMarshalInfo initializes the marshal info.
-func (u *marshalInfo) computeMarshalInfo() {
- u.Lock()
- defer u.Unlock()
- if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
- return
- }
-
- t := u.typ
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.v1extensions = invalidField
- u.sizecache = invalidField
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if reflect.PtrTo(t).Implements(marshalerType) {
- u.hasmarshaler = true
- atomic.StoreInt32(&u.initialized, 1)
- return
- }
-
- // get oneof implementers
- var oneofImplementers []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oneofImplementers = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oneofImplementers = m.XXX_OneofWrappers()
- }
-
- n := t.NumField()
-
- // deal with XXX fields first
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if !strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- switch f.Name {
- case "XXX_sizecache":
- u.sizecache = toField(&f)
- case "XXX_unrecognized":
- u.unrecognized = toField(&f)
- case "XXX_InternalExtensions":
- u.extensions = toField(&f)
- u.messageset = f.Tag.Get("protobuf_messageset") == "1"
- case "XXX_extensions":
- u.v1extensions = toField(&f)
- case "XXX_NoUnkeyedLiteral":
- // nothing to do
- default:
- panic("unknown XXX field: " + f.Name)
- }
- n--
- }
-
- // normal fields
- fields := make([]marshalFieldInfo, n) // batch allocation
- u.fields = make([]*marshalFieldInfo, 0, n)
- for i, j := 0, 0; i < t.NumField(); i++ {
- f := t.Field(i)
-
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- field := &fields[j]
- j++
- field.name = f.Name
- u.fields = append(u.fields, field)
- if f.Tag.Get("protobuf_oneof") != "" {
- field.computeOneofFieldInfo(&f, oneofImplementers)
- continue
- }
- if f.Tag.Get("protobuf") == "" {
- // field has no tag (not in generated message), ignore it
- u.fields = u.fields[:len(u.fields)-1]
- j--
- continue
- }
- field.computeMarshalFieldInfo(&f)
- }
-
- // fields are marshaled in tag order on the wire.
- sort.Sort(byTag(u.fields))
-
- atomic.StoreInt32(&u.initialized, 1)
-}
-
-// helper for sorting fields by tag
-type byTag []*marshalFieldInfo
-
-func (a byTag) Len() int { return len(a) }
-func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
-
-// getExtElemInfo returns the information to marshal an extension element.
-// The info it returns is initialized.
-func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
- // get from cache first
- u.RLock()
- e, ok := u.extElems[desc.Field]
- u.RUnlock()
- if ok {
- return e
- }
-
- t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
- tags := strings.Split(desc.Tag, ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- if t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct {
- t = t.Elem()
- }
- sizer, marshaler := typeMarshaler(t, tags, false, false)
- var deref bool
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- t = reflect.PtrTo(t)
- deref = true
- }
- e = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- isptr: t.Kind() == reflect.Ptr,
- deref: deref,
- }
-
- // update cache
- u.Lock()
- if u.extElems == nil {
- u.extElems = make(map[int32]*marshalElemInfo)
- }
- u.extElems[desc.Field] = e
- u.Unlock()
- return e
-}
-
-// computeMarshalFieldInfo fills up the information to marshal a field.
-func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
- // parse protobuf tag of the field.
- // tag has format of "bytes,49,opt,name=foo,def=hello!"
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- if tags[0] == "" {
- return
- }
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- if tags[2] == "req" {
- fi.required = true
- }
- fi.setTag(f, tag, wt)
- fi.setMarshaler(f, tags)
-}
-
-func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
- fi.field = toField(f)
- fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
- fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
-
- ityp := f.Type // interface type
- for _, o := range oneofImplementers {
- t := reflect.TypeOf(o)
- if !t.Implements(ityp) {
- continue
- }
- sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
- tags := strings.Split(sf.Tag.Get("protobuf"), ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
- fi.oneofElems[t.Elem()] = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- }
- }
-}
-
-// wiretype returns the wire encoding of the type.
-func wiretype(encoding string) uint64 {
- switch encoding {
- case "fixed32":
- return WireFixed32
- case "fixed64":
- return WireFixed64
- case "varint", "zigzag32", "zigzag64":
- return WireVarint
- case "bytes":
- return WireBytes
- case "group":
- return WireStartGroup
- }
- panic("unknown wire type " + encoding)
-}
-
-// setTag fills up the tag (in wire format) and its size in the info of a field.
-func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
- fi.field = toField(f)
- fi.wiretag = uint64(tag)<<3 | wt
- fi.tagsize = SizeVarint(uint64(tag) << 3)
-}
-
-// setMarshaler fills up the sizer and marshaler in the info of a field.
-func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
- switch f.Type.Kind() {
- case reflect.Map:
- // map field
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeMapMarshaler(f)
- return
- case reflect.Ptr, reflect.Slice:
- fi.isPointer = true
- }
- fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
-}
-
-// typeMarshaler returns the sizer and marshaler of a given field.
-// t is the type of the field.
-// tags is the generated "protobuf" tag of the field.
-// If nozero is true, zero value is not marshaled to the wire.
-// If oneof is true, it is a oneof field.
-func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
- encoding := tags[0]
-
- pointer := false
- slice := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- packed := false
- proto3 := false
- validateUTF8 := true
- for i := 2; i < len(tags); i++ {
- if tags[i] == "packed" {
- packed = true
- }
- if tags[i] == "proto3" {
- proto3 = true
- }
- }
- validateUTF8 = validateUTF8 && proto3
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return sizeBoolPtr, appendBoolPtr
- }
- if slice {
- if packed {
- return sizeBoolPackedSlice, appendBoolPackedSlice
- }
- return sizeBoolSlice, appendBoolSlice
- }
- if nozero {
- return sizeBoolValueNoZero, appendBoolValueNoZero
- }
- return sizeBoolValue, appendBoolValue
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixed32Ptr, appendFixed32Ptr
- }
- if slice {
- if packed {
- return sizeFixed32PackedSlice, appendFixed32PackedSlice
- }
- return sizeFixed32Slice, appendFixed32Slice
- }
- if nozero {
- return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
- }
- return sizeFixed32Value, appendFixed32Value
- case "varint":
- if pointer {
- return sizeVarint32Ptr, appendVarint32Ptr
- }
- if slice {
- if packed {
- return sizeVarint32PackedSlice, appendVarint32PackedSlice
- }
- return sizeVarint32Slice, appendVarint32Slice
- }
- if nozero {
- return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
- }
- return sizeVarint32Value, appendVarint32Value
- }
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixedS32Ptr, appendFixedS32Ptr
- }
- if slice {
- if packed {
- return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
- }
- return sizeFixedS32Slice, appendFixedS32Slice
- }
- if nozero {
- return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
- }
- return sizeFixedS32Value, appendFixedS32Value
- case "varint":
- if pointer {
- return sizeVarintS32Ptr, appendVarintS32Ptr
- }
- if slice {
- if packed {
- return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
- }
- return sizeVarintS32Slice, appendVarintS32Slice
- }
- if nozero {
- return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
- }
- return sizeVarintS32Value, appendVarintS32Value
- case "zigzag32":
- if pointer {
- return sizeZigzag32Ptr, appendZigzag32Ptr
- }
- if slice {
- if packed {
- return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
- }
- return sizeZigzag32Slice, appendZigzag32Slice
- }
- if nozero {
- return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
- }
- return sizeZigzag32Value, appendZigzag32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixed64Ptr, appendFixed64Ptr
- }
- if slice {
- if packed {
- return sizeFixed64PackedSlice, appendFixed64PackedSlice
- }
- return sizeFixed64Slice, appendFixed64Slice
- }
- if nozero {
- return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
- }
- return sizeFixed64Value, appendFixed64Value
- case "varint":
- if pointer {
- return sizeVarint64Ptr, appendVarint64Ptr
- }
- if slice {
- if packed {
- return sizeVarint64PackedSlice, appendVarint64PackedSlice
- }
- return sizeVarint64Slice, appendVarint64Slice
- }
- if nozero {
- return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
- }
- return sizeVarint64Value, appendVarint64Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixedS64Ptr, appendFixedS64Ptr
- }
- if slice {
- if packed {
- return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
- }
- return sizeFixedS64Slice, appendFixedS64Slice
- }
- if nozero {
- return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
- }
- return sizeFixedS64Value, appendFixedS64Value
- case "varint":
- if pointer {
- return sizeVarintS64Ptr, appendVarintS64Ptr
- }
- if slice {
- if packed {
- return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
- }
- return sizeVarintS64Slice, appendVarintS64Slice
- }
- if nozero {
- return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
- }
- return sizeVarintS64Value, appendVarintS64Value
- case "zigzag64":
- if pointer {
- return sizeZigzag64Ptr, appendZigzag64Ptr
- }
- if slice {
- if packed {
- return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
- }
- return sizeZigzag64Slice, appendZigzag64Slice
- }
- if nozero {
- return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
- }
- return sizeZigzag64Value, appendZigzag64Value
- }
- case reflect.Float32:
- if pointer {
- return sizeFloat32Ptr, appendFloat32Ptr
- }
- if slice {
- if packed {
- return sizeFloat32PackedSlice, appendFloat32PackedSlice
- }
- return sizeFloat32Slice, appendFloat32Slice
- }
- if nozero {
- return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
- }
- return sizeFloat32Value, appendFloat32Value
- case reflect.Float64:
- if pointer {
- return sizeFloat64Ptr, appendFloat64Ptr
- }
- if slice {
- if packed {
- return sizeFloat64PackedSlice, appendFloat64PackedSlice
- }
- return sizeFloat64Slice, appendFloat64Slice
- }
- if nozero {
- return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
- }
- return sizeFloat64Value, appendFloat64Value
- case reflect.String:
- if validateUTF8 {
- if pointer {
- return sizeStringPtr, appendUTF8StringPtr
- }
- if slice {
- return sizeStringSlice, appendUTF8StringSlice
- }
- if nozero {
- return sizeStringValueNoZero, appendUTF8StringValueNoZero
- }
- return sizeStringValue, appendUTF8StringValue
- }
- if pointer {
- return sizeStringPtr, appendStringPtr
- }
- if slice {
- return sizeStringSlice, appendStringSlice
- }
- if nozero {
- return sizeStringValueNoZero, appendStringValueNoZero
- }
- return sizeStringValue, appendStringValue
- case reflect.Slice:
- if slice {
- return sizeBytesSlice, appendBytesSlice
- }
- if oneof {
- // Oneof bytes field may also have "proto3" tag.
- // We want to marshal it as a oneof field. Do this
- // check before the proto3 check.
- return sizeBytesOneof, appendBytesOneof
- }
- if proto3 {
- return sizeBytes3, appendBytes3
- }
- return sizeBytes, appendBytes
- case reflect.Struct:
- switch encoding {
- case "group":
- if slice {
- return makeGroupSliceMarshaler(getMarshalInfo(t))
- }
- return makeGroupMarshaler(getMarshalInfo(t))
- case "bytes":
- if slice {
- return makeMessageSliceMarshaler(getMarshalInfo(t))
- }
- return makeMessageMarshaler(getMarshalInfo(t))
- }
- }
- panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
-}
-
-// Below are functions to size/marshal a specific type of a field.
-// They are stored in the field's info, and called by function pointers.
-// They have type sizer or marshaler.
-
-func sizeFixed32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixedS32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFloat32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixed64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFixedS64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFloat64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeVarint32Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarint32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarint64Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(*p) + tagsize
-}
-func sizeVarint64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(v) + tagsize
- }
- return n
-}
-func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
- }
- return n
-}
-func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
- }
- return n
-}
-func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeBoolValue(_ pointer, tagsize int) int {
- return 1 + tagsize
-}
-func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toBool()
- if !v {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolPtr(ptr pointer, tagsize int) int {
- p := *ptr.toBoolPtr()
- if p == nil {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- return (1 + tagsize) * len(s)
-}
-func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return 0
- }
- return len(s) + SizeVarint(uint64(len(s))) + tagsize
-}
-func sizeStringValue(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- if v == "" {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringPtr(ptr pointer, tagsize int) int {
- p := *ptr.toStringPtr()
- if p == nil {
- return 0
- }
- v := *p
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringSlice(ptr pointer, tagsize int) int {
- s := *ptr.toStringSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-func sizeBytes(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if v == nil {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytes3(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesOneof(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBytesSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-
-// appendFixed32 appends an encoded fixed32 to b.
-func appendFixed32(b []byte, v uint32) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24))
- return b
-}
-
-// appendFixed64 appends an encoded fixed64 to b.
-func appendFixed64(b []byte, v uint64) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24),
- byte(v>>32),
- byte(v>>40),
- byte(v>>48),
- byte(v>>56))
- return b
-}
-
-// appendVarint appends an encoded varint to b.
-func appendVarint(b []byte, v uint64) []byte {
- // TODO: make 1-byte (maybe 2-byte) case inline-able, once we
- // have non-leaf inliner.
- switch {
- case v < 1<<7:
- b = append(b, byte(v))
- case v < 1<<14:
- b = append(b,
- byte(v&0x7f|0x80),
- byte(v>>7))
- case v < 1<<21:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte(v>>14))
- case v < 1<<28:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte(v>>21))
- case v < 1<<35:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte(v>>28))
- case v < 1<<42:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte(v>>35))
- case v < 1<<49:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte(v>>42))
- case v < 1<<56:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte(v>>49))
- case v < 1<<63:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte(v>>56))
- default:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte((v>>56)&0x7f|0x80),
- 1)
- }
- return b
-}
-
-func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, *p)
- return b, nil
-}
-func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(*p))
- return b, nil
-}
-func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(*p))
- return b, nil
-}
-func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, *p)
- return b, nil
-}
-func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(*p))
- return b, nil
-}
-func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(*p))
- return b, nil
-}
-func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, *p)
- return b, nil
-}
-func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- if !v {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = append(b, 1)
- return b, nil
-}
-
-func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toBoolPtr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- if *p {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(len(s)))
- for _, v := range s {
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- if v == "" {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toStringPtr()
- if p == nil {
- return b, nil
- }
- v := *p
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toStringSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- v := *ptr.toString()
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- v := *ptr.toString()
- if v == "" {
- return b, nil
- }
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- p := *ptr.toStringPtr()
- if p == nil {
- return b, nil
- }
- v := *p
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- s := *ptr.toStringSlice()
- for _, v := range s {
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if v == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBytesSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-
-// makeGroupMarshaler returns the sizer and marshaler for a group.
-// u is the marshal info of the underlying message.
-func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- return u.size(p) + 2*tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- var err error
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, p, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- return b, err
- }
-}
-
-// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
-// u is the marshal info of the underlying message.
-func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- n += u.size(v) + 2*tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err error
- var nerr nonFatal
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, v, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- if !nerr.Merge(err) {
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeMessageMarshaler returns the sizer and marshaler for a message field.
-// u is the marshal info of the message.
-func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- siz := u.size(p)
- return siz + SizeVarint(uint64(siz)) + tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(p)
- b = appendVarint(b, uint64(siz))
- return u.marshal(b, p, deterministic)
- }
-}
-
-// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
-// u is the marshal info of the message.
-func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- siz := u.size(v)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err error
- var nerr nonFatal
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(v)
- b = appendVarint(b, uint64(siz))
- b, err = u.marshal(b, v, deterministic)
-
- if !nerr.Merge(err) {
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeMapMarshaler returns the sizer and marshaler for a map field.
-// f is the pointer to the reflect data structure of the field.
-func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
- // figure out key and value type
- t := f.Type
- keyType := t.Key()
- valType := t.Elem()
- keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
- valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
- keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
- valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
- keyWireTag := 1<<3 | wiretype(keyTags[0])
- valWireTag := 2<<3 | wiretype(valTags[0])
-
- // We create an interface to get the addresses of the map key and value.
- // If value is pointer-typed, the interface is a direct interface, the
- // idata itself is the value. Otherwise, the idata is the pointer to the
- // value.
- // Key cannot be pointer-typed.
- valIsPtr := valType.Kind() == reflect.Ptr
-
- // If value is a message with nested maps, calling
- // valSizer in marshal may be quadratic. We should use
- // cached version in marshal (but not in size).
- // If value is not message type, we don't have size cache,
- // but it cannot be nested either. Just use valSizer.
- valCachedSizer := valSizer
- if valIsPtr && valType.Elem().Kind() == reflect.Struct {
- u := getMarshalInfo(valType.Elem())
- valCachedSizer = func(ptr pointer, tagsize int) int {
- // Same as message sizer, but use cache.
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- siz := u.cachedsize(p)
- return siz + SizeVarint(uint64(siz)) + tagsize
- }
- }
- return func(ptr pointer, tagsize int) int {
- m := ptr.asPointerTo(t).Elem() // the map
- n := 0
- for _, k := range m.MapKeys() {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value
- siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
- m := ptr.asPointerTo(t).Elem() // the map
- var err error
- keys := m.MapKeys()
- if len(keys) > 1 && deterministic {
- sort.Sort(mapKeys(keys))
- }
-
- var nerr nonFatal
- for _, k := range keys {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value
- b = appendVarint(b, tag)
- siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- b = appendVarint(b, uint64(siz))
- b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
- if err != ErrNil && !nerr.Merge(err) { // allow nil value in map
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
-// fi is the marshal info of the field.
-// f is the pointer to the reflect data structure of the field.
-func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
- // Oneof field is an interface. We need to get the actual data type on the fly.
- t := f.Type
- return func(ptr pointer, _ int) int {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return 0
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- e := fi.oneofElems[telem]
- return e.sizer(p, e.tagsize)
- },
- func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return b, nil
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
- return b, errOneofHasNil
- }
- e := fi.oneofElems[telem]
- return e.marshaler(b, p, e.wiretag, deterministic)
- }
-}
-
-// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
-func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- n += len(e.enc)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, ei.tagsize)
- }
- mu.Unlock()
- return n
-}
-
-// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
-func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
- var nerr nonFatal
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
- }
-
- // Sort the keys to provide a deterministic encoding.
- // Not sure this is required, but the old code does it.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// message set format is:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-
-// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
-// in message set format (above).
-func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- for id, e := range m {
- n += 2 // start group, end group. tag = 1 (size=1)
- n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- siz := len(msgWithLen)
- n += siz + 1 // message, tag = 3 (size=1)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, 1) // message, tag = 3 (size=1)
- }
- mu.Unlock()
- return n
-}
-
-// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
-// to the end of byte slice b.
-func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
- var nerr nonFatal
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for id, e := range m {
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- b = append(b, 1<<3|WireEndGroup)
- }
- return b, nerr.E
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, id := range keys {
- e := m[int32(id)]
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- b = append(b, 1<<3|WireEndGroup)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
-func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
- if m == nil {
- return 0
- }
-
- n := 0
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- n += len(e.enc)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, ei.tagsize)
- }
- return n
-}
-
-// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
-func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
- if m == nil {
- return b, nil
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- var err error
- var nerr nonFatal
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, e.enc...)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// newMarshaler is the interface representing objects that can marshal themselves.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newMarshaler interface {
- XXX_Size() int
- XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
-}
-
-// Size returns the encoded size of a protocol buffer message.
-// This is the main entry point.
-func Size(pb Message) int {
- if m, ok := pb.(newMarshaler); ok {
- return m.XXX_Size()
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, _ := m.Marshal()
- return len(b)
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return 0
- }
- var info InternalMessageInfo
- return info.Size(pb)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, returning the data.
-// This is the main entry point.
-func Marshal(pb Message) ([]byte, error) {
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- b := make([]byte, 0, siz)
- return m.XXX_Marshal(b, false)
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- return m.Marshal()
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return nil, ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- b := make([]byte, 0, siz)
- return info.Marshal(b, pb, false)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, writing the result to the
-// Buffer.
-// This is an alternative entry point. It is not necessary to use
-// a Buffer for most applications.
-func (p *Buffer) Marshal(pb Message) error {
- var err error
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = m.XXX_Marshal(p.buf, p.deterministic)
- return err
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, err := m.Marshal()
- p.buf = append(p.buf, b...)
- return err
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
- return err
-}
-
-// grow grows the buffer's capacity, if necessary, to guarantee space for
-// another n bytes. After grow(n), at least n bytes can be written to the
-// buffer without another allocation.
-func (p *Buffer) grow(n int) {
- need := len(p.buf) + n
- if need <= cap(p.buf) {
- return
- }
- newCap := len(p.buf) * 2
- if newCap < need {
- newCap = need
- }
- p.buf = append(make([]byte, 0, newCap), p.buf...)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go
deleted file mode 100644
index 5525def..0000000
--- a/vendor/github.com/golang/protobuf/proto/table_merge.go
+++ /dev/null
@@ -1,654 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-import (
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-// Merge merges the src message into dst.
-// This assumes that dst and src of the same type and are non-nil.
-func (a *InternalMessageInfo) Merge(dst, src Message) {
- mi := atomicLoadMergeInfo(&a.merge)
- if mi == nil {
- mi = getMergeInfo(reflect.TypeOf(dst).Elem())
- atomicStoreMergeInfo(&a.merge, mi)
- }
- mi.merge(toPointer(&dst), toPointer(&src))
-}
-
-type mergeInfo struct {
- typ reflect.Type
-
- initialized int32 // 0: only typ is valid, 1: everything is valid
- lock sync.Mutex
-
- fields []mergeFieldInfo
- unrecognized field // Offset of XXX_unrecognized
-}
-
-type mergeFieldInfo struct {
- field field // Offset of field, guaranteed to be valid
-
- // isPointer reports whether the value in the field is a pointer.
- // This is true for the following situations:
- // * Pointer to struct
- // * Pointer to basic type (proto2 only)
- // * Slice (first value in slice header is a pointer)
- // * String (first value in string header is a pointer)
- isPointer bool
-
- // basicWidth reports the width of the field assuming that it is directly
- // embedded in the struct (as is the case for basic types in proto3).
- // The possible values are:
- // 0: invalid
- // 1: bool
- // 4: int32, uint32, float32
- // 8: int64, uint64, float64
- basicWidth int
-
- // Where dst and src are pointers to the types being merged.
- merge func(dst, src pointer)
-}
-
-var (
- mergeInfoMap = map[reflect.Type]*mergeInfo{}
- mergeInfoLock sync.Mutex
-)
-
-func getMergeInfo(t reflect.Type) *mergeInfo {
- mergeInfoLock.Lock()
- defer mergeInfoLock.Unlock()
- mi := mergeInfoMap[t]
- if mi == nil {
- mi = &mergeInfo{typ: t}
- mergeInfoMap[t] = mi
- }
- return mi
-}
-
-// merge merges src into dst assuming they are both of type *mi.typ.
-func (mi *mergeInfo) merge(dst, src pointer) {
- if dst.isNil() {
- panic("proto: nil destination")
- }
- if src.isNil() {
- return // Nothing to do.
- }
-
- if atomic.LoadInt32(&mi.initialized) == 0 {
- mi.computeMergeInfo()
- }
-
- for _, fi := range mi.fields {
- sfp := src.offset(fi.field)
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string
- continue
- }
- if fi.basicWidth > 0 {
- switch {
- case fi.basicWidth == 1 && !*sfp.toBool():
- continue
- case fi.basicWidth == 4 && *sfp.toUint32() == 0:
- continue
- case fi.basicWidth == 8 && *sfp.toUint64() == 0:
- continue
- }
- }
- }
-
- dfp := dst.offset(fi.field)
- fi.merge(dfp, sfp)
- }
-
- // TODO: Make this faster?
- out := dst.asPointerTo(mi.typ).Elem()
- in := src.asPointerTo(mi.typ).Elem()
- if emIn, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- if mi.unrecognized.IsValid() {
- if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 {
- *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...)
- }
- }
-}
-
-func (mi *mergeInfo) computeMergeInfo() {
- mi.lock.Lock()
- defer mi.lock.Unlock()
- if mi.initialized != 0 {
- return
- }
- t := mi.typ
- n := t.NumField()
-
- props := GetProperties(t)
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
-
- mfi := mergeFieldInfo{field: toField(&f)}
- tf := f.Type
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- switch tf.Kind() {
- case reflect.Ptr, reflect.Slice, reflect.String:
- // As a special case, we assume slices and strings are pointers
- // since we know that the first field in the SliceSlice or
- // StringHeader is a data pointer.
- mfi.isPointer = true
- case reflect.Bool:
- mfi.basicWidth = 1
- case reflect.Int32, reflect.Uint32, reflect.Float32:
- mfi.basicWidth = 4
- case reflect.Int64, reflect.Uint64, reflect.Float64:
- mfi.basicWidth = 8
- }
- }
-
- // Unwrap tf to get at its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + tf.Name())
- }
-
- switch tf.Kind() {
- case reflect.Int32:
- switch {
- case isSlice: // E.g., []int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Slice is not defined (see pointer_reflect.go).
- /*
- sfsp := src.toInt32Slice()
- if *sfsp != nil {
- dfsp := dst.toInt32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- */
- sfs := src.getInt32Slice()
- if sfs != nil {
- dfs := dst.getInt32Slice()
- dfs = append(dfs, sfs...)
- if dfs == nil {
- dfs = []int32{}
- }
- dst.setInt32Slice(dfs)
- }
- }
- case isPointer: // E.g., *int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Ptr is not defined (see pointer_reflect.go).
- /*
- sfpp := src.toInt32Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt32Ptr()
- if *dfpp == nil {
- *dfpp = Int32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- */
- sfp := src.getInt32Ptr()
- if sfp != nil {
- dfp := dst.getInt32Ptr()
- if dfp == nil {
- dst.setInt32Ptr(*sfp)
- } else {
- *dfp = *sfp
- }
- }
- }
- default: // E.g., int32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt32(); v != 0 {
- *dst.toInt32() = v
- }
- }
- }
- case reflect.Int64:
- switch {
- case isSlice: // E.g., []int64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toInt64Slice()
- if *sfsp != nil {
- dfsp := dst.toInt64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- }
- case isPointer: // E.g., *int64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toInt64Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt64Ptr()
- if *dfpp == nil {
- *dfpp = Int64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., int64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt64(); v != 0 {
- *dst.toInt64() = v
- }
- }
- }
- case reflect.Uint32:
- switch {
- case isSlice: // E.g., []uint32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint32Slice()
- if *sfsp != nil {
- dfsp := dst.toUint32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint32{}
- }
- }
- }
- case isPointer: // E.g., *uint32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint32Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint32Ptr()
- if *dfpp == nil {
- *dfpp = Uint32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint32(); v != 0 {
- *dst.toUint32() = v
- }
- }
- }
- case reflect.Uint64:
- switch {
- case isSlice: // E.g., []uint64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint64Slice()
- if *sfsp != nil {
- dfsp := dst.toUint64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint64{}
- }
- }
- }
- case isPointer: // E.g., *uint64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint64Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint64Ptr()
- if *dfpp == nil {
- *dfpp = Uint64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint64(); v != 0 {
- *dst.toUint64() = v
- }
- }
- }
- case reflect.Float32:
- switch {
- case isSlice: // E.g., []float32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat32Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float32{}
- }
- }
- }
- case isPointer: // E.g., *float32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat32Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat32Ptr()
- if *dfpp == nil {
- *dfpp = Float32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat32(); v != 0 {
- *dst.toFloat32() = v
- }
- }
- }
- case reflect.Float64:
- switch {
- case isSlice: // E.g., []float64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat64Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float64{}
- }
- }
- }
- case isPointer: // E.g., *float64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat64Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat64Ptr()
- if *dfpp == nil {
- *dfpp = Float64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat64(); v != 0 {
- *dst.toFloat64() = v
- }
- }
- }
- case reflect.Bool:
- switch {
- case isSlice: // E.g., []bool
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toBoolSlice()
- if *sfsp != nil {
- dfsp := dst.toBoolSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []bool{}
- }
- }
- }
- case isPointer: // E.g., *bool
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toBoolPtr()
- if *sfpp != nil {
- dfpp := dst.toBoolPtr()
- if *dfpp == nil {
- *dfpp = Bool(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., bool
- mfi.merge = func(dst, src pointer) {
- if v := *src.toBool(); v {
- *dst.toBool() = v
- }
- }
- }
- case reflect.String:
- switch {
- case isSlice: // E.g., []string
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toStringSlice()
- if *sfsp != nil {
- dfsp := dst.toStringSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []string{}
- }
- }
- }
- case isPointer: // E.g., *string
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toStringPtr()
- if *sfpp != nil {
- dfpp := dst.toStringPtr()
- if *dfpp == nil {
- *dfpp = String(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., string
- mfi.merge = func(dst, src pointer) {
- if v := *src.toString(); v != "" {
- *dst.toString() = v
- }
- }
- }
- case reflect.Slice:
- isProto3 := props.Prop[i].proto3
- switch {
- case isPointer:
- panic("bad pointer in byte slice case in " + tf.Name())
- case tf.Elem().Kind() != reflect.Uint8:
- panic("bad element kind in byte slice case in " + tf.Name())
- case isSlice: // E.g., [][]byte
- mfi.merge = func(dst, src pointer) {
- sbsp := src.toBytesSlice()
- if *sbsp != nil {
- dbsp := dst.toBytesSlice()
- for _, sb := range *sbsp {
- if sb == nil {
- *dbsp = append(*dbsp, nil)
- } else {
- *dbsp = append(*dbsp, append([]byte{}, sb...))
- }
- }
- if *dbsp == nil {
- *dbsp = [][]byte{}
- }
- }
- }
- default: // E.g., []byte
- mfi.merge = func(dst, src pointer) {
- sbp := src.toBytes()
- if *sbp != nil {
- dbp := dst.toBytes()
- if !isProto3 || len(*sbp) > 0 {
- *dbp = append([]byte{}, *sbp...)
- }
- }
- }
- }
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("message field %s without pointer", tf))
- case isSlice: // E.g., []*pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sps := src.getPointerSlice()
- if sps != nil {
- dps := dst.getPointerSlice()
- for _, sp := range sps {
- var dp pointer
- if !sp.isNil() {
- dp = valToPointer(reflect.New(tf))
- mi.merge(dp, sp)
- }
- dps = append(dps, dp)
- }
- if dps == nil {
- dps = []pointer{}
- }
- dst.setPointerSlice(dps)
- }
- }
- default: // E.g., *pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sp := src.getPointer()
- if !sp.isNil() {
- dp := dst.getPointer()
- if dp.isNil() {
- dp = valToPointer(reflect.New(tf))
- dst.setPointer(dp)
- }
- mi.merge(dp, sp)
- }
- }
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in map case in " + tf.Name())
- default: // E.g., map[K]V
- mfi.merge = func(dst, src pointer) {
- sm := src.asPointerTo(tf).Elem()
- if sm.Len() == 0 {
- return
- }
- dm := dst.asPointerTo(tf).Elem()
- if dm.IsNil() {
- dm.Set(reflect.MakeMap(tf))
- }
-
- switch tf.Elem().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(Clone(val.Interface().(Message)))
- dm.SetMapIndex(key, val)
- }
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- dm.SetMapIndex(key, val)
- }
- default: // Basic type (e.g., string)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- dm.SetMapIndex(key, val)
- }
- }
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in interface case in " + tf.Name())
- default: // E.g., interface{}
- // TODO: Make this faster?
- mfi.merge = func(dst, src pointer) {
- su := src.asPointerTo(tf).Elem()
- if !su.IsNil() {
- du := dst.asPointerTo(tf).Elem()
- typ := su.Elem().Type()
- if du.IsNil() || du.Elem().Type() != typ {
- du.Set(reflect.New(typ.Elem())) // Initialize interface if empty
- }
- sv := su.Elem().Elem().Field(0)
- if sv.Kind() == reflect.Ptr && sv.IsNil() {
- return
- }
- dv := du.Elem().Elem().Field(0)
- if dv.Kind() == reflect.Ptr && dv.IsNil() {
- dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty
- }
- switch sv.Type().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- Merge(dv.Interface().(Message), sv.Interface().(Message))
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...)))
- default: // Basic type (e.g., string)
- dv.Set(sv)
- }
- }
- }
- }
- default:
- panic(fmt.Sprintf("merger not found for type:%s", tf))
- }
- mi.fields = append(mi.fields, mfi)
- }
-
- mi.unrecognized = invalidField
- if f, ok := t.FieldByName("XXX_unrecognized"); ok {
- if f.Type != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- mi.unrecognized = toField(&f)
- }
-
- atomic.StoreInt32(&mi.initialized, 1)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
deleted file mode 100644
index acee2fc..0000000
--- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
+++ /dev/null
@@ -1,2053 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-import (
- "errors"
- "fmt"
- "io"
- "math"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// Unmarshal is the entry point from the generated .pb.go files.
-// This function is not intended to be used by non-generated code.
-// This function is not subject to any compatibility guarantee.
-// msg contains a pointer to a protocol buffer struct.
-// b is the data to be unmarshaled into the protocol buffer.
-// a is a pointer to a place to store cached unmarshal information.
-func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error {
- // Load the unmarshal information for this message type.
- // The atomic load ensures memory consistency.
- u := atomicLoadUnmarshalInfo(&a.unmarshal)
- if u == nil {
- // Slow path: find unmarshal info for msg, update a with it.
- u = getUnmarshalInfo(reflect.TypeOf(msg).Elem())
- atomicStoreUnmarshalInfo(&a.unmarshal, u)
- }
- // Then do the unmarshaling.
- err := u.unmarshal(toPointer(&msg), b)
- return err
-}
-
-type unmarshalInfo struct {
- typ reflect.Type // type of the protobuf struct
-
- // 0 = only typ field is initialized
- // 1 = completely initialized
- initialized int32
- lock sync.Mutex // prevents double initialization
- dense []unmarshalFieldInfo // fields indexed by tag #
- sparse map[uint64]unmarshalFieldInfo // fields indexed by tag #
- reqFields []string // names of required fields
- reqMask uint64 // 1< 0 {
- // Read tag and wire type.
- // Special case 1 and 2 byte varints.
- var x uint64
- if b[0] < 128 {
- x = uint64(b[0])
- b = b[1:]
- } else if len(b) >= 2 && b[1] < 128 {
- x = uint64(b[0]&0x7f) + uint64(b[1])<<7
- b = b[2:]
- } else {
- var n int
- x, n = decodeVarint(b)
- if n == 0 {
- return io.ErrUnexpectedEOF
- }
- b = b[n:]
- }
- tag := x >> 3
- wire := int(x) & 7
-
- // Dispatch on the tag to one of the unmarshal* functions below.
- var f unmarshalFieldInfo
- if tag < uint64(len(u.dense)) {
- f = u.dense[tag]
- } else {
- f = u.sparse[tag]
- }
- if fn := f.unmarshal; fn != nil {
- var err error
- b, err = fn(b, m.offset(f.field), wire)
- if err == nil {
- reqMask |= f.reqMask
- continue
- }
- if r, ok := err.(*RequiredNotSetError); ok {
- // Remember this error, but keep parsing. We need to produce
- // a full parse even if a required field is missing.
- if errLater == nil {
- errLater = r
- }
- reqMask |= f.reqMask
- continue
- }
- if err != errInternalBadWireType {
- if err == errInvalidUTF8 {
- if errLater == nil {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- errLater = &invalidUTF8Error{fullName}
- }
- continue
- }
- return err
- }
- // Fragments with bad wire type are treated as unknown fields.
- }
-
- // Unknown tag.
- if !u.unrecognized.IsValid() {
- // Don't keep unrecognized data; just skip it.
- var err error
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- continue
- }
- // Keep unrecognized data around.
- // maybe in extensions, maybe in the unrecognized field.
- z := m.offset(u.unrecognized).toBytes()
- var emap map[int32]Extension
- var e Extension
- for _, r := range u.extensionRanges {
- if uint64(r.Start) <= tag && tag <= uint64(r.End) {
- if u.extensions.IsValid() {
- mp := m.offset(u.extensions).toExtensions()
- emap = mp.extensionsWrite()
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- if u.oldExtensions.IsValid() {
- p := m.offset(u.oldExtensions).toOldExtensions()
- emap = *p
- if emap == nil {
- emap = map[int32]Extension{}
- *p = emap
- }
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- panic("no extensions field available")
- }
- }
-
- // Use wire type to skip data.
- var err error
- b0 := b
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- *z = encodeVarint(*z, tag<<3|uint64(wire))
- *z = append(*z, b0[:len(b0)-len(b)]...)
-
- if emap != nil {
- emap[int32(tag)] = e
- }
- }
- if reqMask != u.reqMask && errLater == nil {
- // A required field of this message is missing.
- for _, n := range u.reqFields {
- if reqMask&1 == 0 {
- errLater = &RequiredNotSetError{n}
- }
- reqMask >>= 1
- }
- }
- return errLater
-}
-
-// computeUnmarshalInfo fills in u with information for use
-// in unmarshaling protocol buffers of type u.typ.
-func (u *unmarshalInfo) computeUnmarshalInfo() {
- u.lock.Lock()
- defer u.lock.Unlock()
- if u.initialized != 0 {
- return
- }
- t := u.typ
- n := t.NumField()
-
- // Set up the "not found" value for the unrecognized byte buffer.
- // This is the default for proto3.
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.oldExtensions = invalidField
-
- // List of the generated type and offset for each oneof field.
- type oneofField struct {
- ityp reflect.Type // interface type of oneof field
- field field // offset in containing message
- }
- var oneofFields []oneofField
-
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if f.Name == "XXX_unrecognized" {
- // The byte slice used to hold unrecognized input is special.
- if f.Type != reflect.TypeOf(([]byte)(nil)) {
- panic("bad type for XXX_unrecognized field: " + f.Type.Name())
- }
- u.unrecognized = toField(&f)
- continue
- }
- if f.Name == "XXX_InternalExtensions" {
- // Ditto here.
- if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) {
- panic("bad type for XXX_InternalExtensions field: " + f.Type.Name())
- }
- u.extensions = toField(&f)
- if f.Tag.Get("protobuf_messageset") == "1" {
- u.isMessageSet = true
- }
- continue
- }
- if f.Name == "XXX_extensions" {
- // An older form of the extensions field.
- if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) {
- panic("bad type for XXX_extensions field: " + f.Type.Name())
- }
- u.oldExtensions = toField(&f)
- continue
- }
- if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" {
- continue
- }
-
- oneof := f.Tag.Get("protobuf_oneof")
- if oneof != "" {
- oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)})
- // The rest of oneof processing happens below.
- continue
- }
-
- tags := f.Tag.Get("protobuf")
- tagArray := strings.Split(tags, ",")
- if len(tagArray) < 2 {
- panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags)
- }
- tag, err := strconv.Atoi(tagArray[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tagArray[1])
- }
-
- name := ""
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- }
-
- // Extract unmarshaling function from the field (its type and tags).
- unmarshal := fieldUnmarshaler(&f)
-
- // Required field?
- var reqMask uint64
- if tagArray[2] == "req" {
- bit := len(u.reqFields)
- u.reqFields = append(u.reqFields, name)
- reqMask = uint64(1) << uint(bit)
- // TODO: if we have more than 64 required fields, we end up
- // not verifying that all required fields are present.
- // Fix this, perhaps using a count of required fields?
- }
-
- // Store the info in the correct slot in the message.
- u.setTag(tag, toField(&f), unmarshal, reqMask, name)
- }
-
- // Find any types associated with oneof fields.
- var oneofImplementers []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oneofImplementers = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oneofImplementers = m.XXX_OneofWrappers()
- }
- for _, v := range oneofImplementers {
- tptr := reflect.TypeOf(v) // *Msg_X
- typ := tptr.Elem() // Msg_X
-
- f := typ.Field(0) // oneof implementers have one field
- baseUnmarshal := fieldUnmarshaler(&f)
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- fieldNum, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tags[1])
- }
- var name string
- for _, tag := range tags {
- if strings.HasPrefix(tag, "name=") {
- name = strings.TrimPrefix(tag, "name=")
- break
- }
- }
-
- // Find the oneof field that this struct implements.
- // Might take O(n^2) to process all of the oneofs, but who cares.
- for _, of := range oneofFields {
- if tptr.Implements(of.ityp) {
- // We have found the corresponding interface for this struct.
- // That lets us know where this struct should be stored
- // when we encounter it during unmarshaling.
- unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal)
- u.setTag(fieldNum, of.field, unmarshal, 0, name)
- }
- }
-
- }
-
- // Get extension ranges, if any.
- fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray")
- if fn.IsValid() {
- if !u.extensions.IsValid() && !u.oldExtensions.IsValid() {
- panic("a message with extensions, but no extensions field in " + t.Name())
- }
- u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange)
- }
-
- // Explicitly disallow tag 0. This will ensure we flag an error
- // when decoding a buffer of all zeros. Without this code, we
- // would decode and skip an all-zero buffer of even length.
- // [0 0] is [tag=0/wiretype=varint varint-encoded-0].
- u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) {
- return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w)
- }, 0, "")
-
- // Set mask for required field check.
- u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here?
- for len(u.dense) <= tag {
- u.dense = append(u.dense, unmarshalFieldInfo{})
- }
- u.dense[tag] = i
- return
- }
- if u.sparse == nil {
- u.sparse = map[uint64]unmarshalFieldInfo{}
- }
- u.sparse[uint64(tag)] = i
-}
-
-// fieldUnmarshaler returns an unmarshaler for the given field.
-func fieldUnmarshaler(f *reflect.StructField) unmarshaler {
- if f.Type.Kind() == reflect.Map {
- return makeUnmarshalMap(f)
- }
- return typeUnmarshaler(f.Type, f.Tag.Get("protobuf"))
-}
-
-// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair.
-func typeUnmarshaler(t reflect.Type, tags string) unmarshaler {
- tagArray := strings.Split(tags, ",")
- encoding := tagArray[0]
- name := "unknown"
- proto3 := false
- validateUTF8 := true
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- if tag == "proto3" {
- proto3 = true
- }
- }
- validateUTF8 = validateUTF8 && proto3
-
- // Figure out packaging (pointer, slice, or both)
- slice := false
- pointer := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- // We'll never have both pointer and slice for basic types.
- if pointer && slice && t.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + t.Name())
- }
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return unmarshalBoolPtr
- }
- if slice {
- return unmarshalBoolSlice
- }
- return unmarshalBoolValue
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixedS32Ptr
- }
- if slice {
- return unmarshalFixedS32Slice
- }
- return unmarshalFixedS32Value
- case "varint":
- // this could be int32 or enum
- if pointer {
- return unmarshalInt32Ptr
- }
- if slice {
- return unmarshalInt32Slice
- }
- return unmarshalInt32Value
- case "zigzag32":
- if pointer {
- return unmarshalSint32Ptr
- }
- if slice {
- return unmarshalSint32Slice
- }
- return unmarshalSint32Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixedS64Ptr
- }
- if slice {
- return unmarshalFixedS64Slice
- }
- return unmarshalFixedS64Value
- case "varint":
- if pointer {
- return unmarshalInt64Ptr
- }
- if slice {
- return unmarshalInt64Slice
- }
- return unmarshalInt64Value
- case "zigzag64":
- if pointer {
- return unmarshalSint64Ptr
- }
- if slice {
- return unmarshalSint64Slice
- }
- return unmarshalSint64Value
- }
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixed32Ptr
- }
- if slice {
- return unmarshalFixed32Slice
- }
- return unmarshalFixed32Value
- case "varint":
- if pointer {
- return unmarshalUint32Ptr
- }
- if slice {
- return unmarshalUint32Slice
- }
- return unmarshalUint32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixed64Ptr
- }
- if slice {
- return unmarshalFixed64Slice
- }
- return unmarshalFixed64Value
- case "varint":
- if pointer {
- return unmarshalUint64Ptr
- }
- if slice {
- return unmarshalUint64Slice
- }
- return unmarshalUint64Value
- }
- case reflect.Float32:
- if pointer {
- return unmarshalFloat32Ptr
- }
- if slice {
- return unmarshalFloat32Slice
- }
- return unmarshalFloat32Value
- case reflect.Float64:
- if pointer {
- return unmarshalFloat64Ptr
- }
- if slice {
- return unmarshalFloat64Slice
- }
- return unmarshalFloat64Value
- case reflect.Map:
- panic("map type in typeUnmarshaler in " + t.Name())
- case reflect.Slice:
- if pointer {
- panic("bad pointer in slice case in " + t.Name())
- }
- if slice {
- return unmarshalBytesSlice
- }
- return unmarshalBytesValue
- case reflect.String:
- if validateUTF8 {
- if pointer {
- return unmarshalUTF8StringPtr
- }
- if slice {
- return unmarshalUTF8StringSlice
- }
- return unmarshalUTF8StringValue
- }
- if pointer {
- return unmarshalStringPtr
- }
- if slice {
- return unmarshalStringSlice
- }
- return unmarshalStringValue
- case reflect.Struct:
- // message or group field
- if !pointer {
- panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding))
- }
- switch encoding {
- case "bytes":
- if slice {
- return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name)
- case "group":
- if slice {
- return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name)
- }
- }
- panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding))
-}
-
-// Below are all the unmarshalers for individual fields of various types.
-
-func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64() = v
- return b, nil
-}
-
-func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32() = v
- return b, nil
-}
-
-func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64() = v
- return b[8:], nil
-}
-
-func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64() = v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32() = v
- return b[4:], nil
-}
-
-func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- *f.toInt32() = v
- return b[4:], nil
-}
-
-func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.setInt32Ptr(v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- return b[4:], nil
-}
-
-func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- // Note: any length varint is allowed, even though any sane
- // encoder will use one byte.
- // See https://github.com/golang/protobuf/issues/76
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- // TODO: check if x>1? Tests seem to indicate no.
- v := x != 0
- *f.toBool() = v
- return b[n:], nil
-}
-
-func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- *f.toBoolPtr() = &v
- return b[n:], nil
-}
-
-func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- b = b[n:]
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- return b[n:], nil
-}
-
-func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64() = v
- return b[8:], nil
-}
-
-func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32() = v
- return b[4:], nil
-}
-
-func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toString() = v
- return b[x:], nil
-}
-
-func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toStringPtr() = &v
- return b[x:], nil
-}
-
-func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- s := f.toStringSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toString() = v
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toStringPtr() = &v
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- s := f.toStringSlice()
- *s = append(*s, v)
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-var emptyBuf [0]byte
-
-func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // The use of append here is a trick which avoids the zeroing
- // that would be required if we used a make/copy pair.
- // We append to emptyBuf instead of nil because we want
- // a non-nil result even when the length is 0.
- v := append(emptyBuf[:], b[:x]...)
- *f.toBytes() = v
- return b[x:], nil
-}
-
-func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := append(emptyBuf[:], b[:x]...)
- s := f.toBytesSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // First read the message field to see if something is there.
- // The semantics of multiple submessages are weird. Instead of
- // the last one winning (as it is for all other fields), multiple
- // submessages are merged.
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[x:], err
- }
-}
-
-func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[x:], err
- }
-}
-
-func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[y:], err
- }
-}
-
-func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[y:], err
- }
-}
-
-func makeUnmarshalMap(f *reflect.StructField) unmarshaler {
- t := f.Type
- kt := t.Key()
- vt := t.Elem()
- unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key"))
- unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val"))
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // The map entry is a submessage. Figure out how big it is.
- if w != WireBytes {
- return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes)
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- r := b[x:] // unused data to return
- b = b[:x] // data for map entry
-
- // Note: we could use #keys * #values ~= 200 functions
- // to do map decoding without reflection. Probably not worth it.
- // Maps will be somewhat slow. Oh well.
-
- // Read key and value from data.
- var nerr nonFatal
- k := reflect.New(kt)
- v := reflect.New(vt)
- for len(b) > 0 {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- wire := int(x) & 7
- b = b[n:]
-
- var err error
- switch x >> 3 {
- case 1:
- b, err = unmarshalKey(b, valToPointer(k), wire)
- case 2:
- b, err = unmarshalVal(b, valToPointer(v), wire)
- default:
- err = errInternalBadWireType // skip unknown tag
- }
-
- if nerr.Merge(err) {
- continue
- }
- if err != errInternalBadWireType {
- return nil, err
- }
-
- // Skip past unknown fields.
- b, err = skipField(b, wire)
- if err != nil {
- return nil, err
- }
- }
-
- // Get map, allocate if needed.
- m := f.asPointerTo(t).Elem() // an addressable map[K]T
- if m.IsNil() {
- m.Set(reflect.MakeMap(t))
- }
-
- // Insert into map.
- m.SetMapIndex(k.Elem(), v.Elem())
-
- return r, nerr.E
- }
-}
-
-// makeUnmarshalOneof makes an unmarshaler for oneof fields.
-// for:
-// message Msg {
-// oneof F {
-// int64 X = 1;
-// float64 Y = 2;
-// }
-// }
-// typ is the type of the concrete entry for a oneof case (e.g. Msg_X).
-// ityp is the interface type of the oneof field (e.g. isMsg_F).
-// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64).
-// Note that this function will be called once for each case in the oneof.
-func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler {
- sf := typ.Field(0)
- field0 := toField(&sf)
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // Allocate holder for value.
- v := reflect.New(typ)
-
- // Unmarshal data into holder.
- // We unmarshal into the first field of the holder object.
- var err error
- var nerr nonFatal
- b, err = unmarshal(b, valToPointer(v).offset(field0), w)
- if !nerr.Merge(err) {
- return nil, err
- }
-
- // Write pointer to holder into target field.
- f.asPointerTo(ityp).Elem().Set(v)
-
- return b, nerr.E
- }
-}
-
-// Error used by decode internally.
-var errInternalBadWireType = errors.New("proto: internal error: bad wiretype")
-
-// skipField skips past a field of type wire and returns the remaining bytes.
-func skipField(b []byte, wire int) ([]byte, error) {
- switch wire {
- case WireVarint:
- _, k := decodeVarint(b)
- if k == 0 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[k:]
- case WireFixed32:
- if len(b) < 4 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[4:]
- case WireFixed64:
- if len(b) < 8 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[8:]
- case WireBytes:
- m, k := decodeVarint(b)
- if k == 0 || uint64(len(b)-k) < m {
- return b, io.ErrUnexpectedEOF
- }
- b = b[uint64(k)+m:]
- case WireStartGroup:
- _, i := findEndGroup(b)
- if i == -1 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[i:]
- default:
- return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire)
- }
- return b, nil
-}
-
-// findEndGroup finds the index of the next EndGroup tag.
-// Groups may be nested, so the "next" EndGroup tag is the first
-// unpaired EndGroup.
-// findEndGroup returns the indexes of the start and end of the EndGroup tag.
-// Returns (-1,-1) if it can't find one.
-func findEndGroup(b []byte) (int, int) {
- depth := 1
- i := 0
- for {
- x, n := decodeVarint(b[i:])
- if n == 0 {
- return -1, -1
- }
- j := i
- i += n
- switch x & 7 {
- case WireVarint:
- _, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- case WireFixed32:
- if len(b)-4 < i {
- return -1, -1
- }
- i += 4
- case WireFixed64:
- if len(b)-8 < i {
- return -1, -1
- }
- i += 8
- case WireBytes:
- m, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- if uint64(len(b)-i) < m {
- return -1, -1
- }
- i += int(m)
- case WireStartGroup:
- depth++
- case WireEndGroup:
- depth--
- if depth == 0 {
- return j, i
- }
- default:
- return -1, -1
- }
- }
-}
-
-// encodeVarint appends a varint-encoded integer to b and returns the result.
-func encodeVarint(b []byte, x uint64) []byte {
- for x >= 1<<7 {
- b = append(b, byte(x&0x7f|0x80))
- x >>= 7
- }
- return append(b, byte(x))
-}
-
-// decodeVarint reads a varint-encoded integer from b.
-// Returns the decoded integer and the number of bytes read.
-// If there is an error, it returns 0,0.
-func decodeVarint(b []byte) (uint64, int) {
- var x, y uint64
- if len(b) == 0 {
- goto bad
- }
- x = uint64(b[0])
- if x < 0x80 {
- return x, 1
- }
- x -= 0x80
-
- if len(b) <= 1 {
- goto bad
- }
- y = uint64(b[1])
- x += y << 7
- if y < 0x80 {
- return x, 2
- }
- x -= 0x80 << 7
-
- if len(b) <= 2 {
- goto bad
- }
- y = uint64(b[2])
- x += y << 14
- if y < 0x80 {
- return x, 3
- }
- x -= 0x80 << 14
-
- if len(b) <= 3 {
- goto bad
- }
- y = uint64(b[3])
- x += y << 21
- if y < 0x80 {
- return x, 4
- }
- x -= 0x80 << 21
-
- if len(b) <= 4 {
- goto bad
- }
- y = uint64(b[4])
- x += y << 28
- if y < 0x80 {
- return x, 5
- }
- x -= 0x80 << 28
-
- if len(b) <= 5 {
- goto bad
- }
- y = uint64(b[5])
- x += y << 35
- if y < 0x80 {
- return x, 6
- }
- x -= 0x80 << 35
-
- if len(b) <= 6 {
- goto bad
- }
- y = uint64(b[6])
- x += y << 42
- if y < 0x80 {
- return x, 7
- }
- x -= 0x80 << 42
-
- if len(b) <= 7 {
- goto bad
- }
- y = uint64(b[7])
- x += y << 49
- if y < 0x80 {
- return x, 8
- }
- x -= 0x80 << 49
-
- if len(b) <= 8 {
- goto bad
- }
- y = uint64(b[8])
- x += y << 56
- if y < 0x80 {
- return x, 9
- }
- x -= 0x80 << 56
-
- if len(b) <= 9 {
- goto bad
- }
- y = uint64(b[9])
- x += y << 63
- if y < 2 {
- return x, 10
- }
-
-bad:
- return 0, 0
-}
diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go
deleted file mode 100644
index 1aaee72..0000000
--- a/vendor/github.com/golang/protobuf/proto/text.go
+++ /dev/null
@@ -1,843 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-// Functions for writing the text protocol buffer format.
-
-import (
- "bufio"
- "bytes"
- "encoding"
- "errors"
- "fmt"
- "io"
- "log"
- "math"
- "reflect"
- "sort"
- "strings"
-)
-
-var (
- newline = []byte("\n")
- spaces = []byte(" ")
- endBraceNewline = []byte("}\n")
- backslashN = []byte{'\\', 'n'}
- backslashR = []byte{'\\', 'r'}
- backslashT = []byte{'\\', 't'}
- backslashDQ = []byte{'\\', '"'}
- backslashBS = []byte{'\\', '\\'}
- posInf = []byte("inf")
- negInf = []byte("-inf")
- nan = []byte("nan")
-)
-
-type writer interface {
- io.Writer
- WriteByte(byte) error
-}
-
-// textWriter is an io.Writer that tracks its indentation level.
-type textWriter struct {
- ind int
- complete bool // if the current position is a complete line
- compact bool // whether to write out as a one-liner
- w writer
-}
-
-func (w *textWriter) WriteString(s string) (n int, err error) {
- if !strings.Contains(s, "\n") {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- w.complete = false
- return io.WriteString(w.w, s)
- }
- // WriteString is typically called without newlines, so this
- // codepath and its copy are rare. We copy to avoid
- // duplicating all of Write's logic here.
- return w.Write([]byte(s))
-}
-
-func (w *textWriter) Write(p []byte) (n int, err error) {
- newlines := bytes.Count(p, newline)
- if newlines == 0 {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- n, err = w.w.Write(p)
- w.complete = false
- return n, err
- }
-
- frags := bytes.SplitN(p, newline, newlines+1)
- if w.compact {
- for i, frag := range frags {
- if i > 0 {
- if err := w.w.WriteByte(' '); err != nil {
- return n, err
- }
- n++
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- }
- return n, nil
- }
-
- for i, frag := range frags {
- if w.complete {
- w.writeIndent()
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- if i+1 < len(frags) {
- if err := w.w.WriteByte('\n'); err != nil {
- return n, err
- }
- n++
- }
- }
- w.complete = len(frags[len(frags)-1]) == 0
- return n, nil
-}
-
-func (w *textWriter) WriteByte(c byte) error {
- if w.compact && c == '\n' {
- c = ' '
- }
- if !w.compact && w.complete {
- w.writeIndent()
- }
- err := w.w.WriteByte(c)
- w.complete = c == '\n'
- return err
-}
-
-func (w *textWriter) indent() { w.ind++ }
-
-func (w *textWriter) unindent() {
- if w.ind == 0 {
- log.Print("proto: textWriter unindented too far")
- return
- }
- w.ind--
-}
-
-func writeName(w *textWriter, props *Properties) error {
- if _, err := w.WriteString(props.OrigName); err != nil {
- return err
- }
- if props.Wire != "group" {
- return w.WriteByte(':')
- }
- return nil
-}
-
-func requiresQuotes(u string) bool {
- // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
- for _, ch := range u {
- switch {
- case ch == '.' || ch == '/' || ch == '_':
- continue
- case '0' <= ch && ch <= '9':
- continue
- case 'A' <= ch && ch <= 'Z':
- continue
- case 'a' <= ch && ch <= 'z':
- continue
- default:
- return true
- }
- }
- return false
-}
-
-// isAny reports whether sv is a google.protobuf.Any message
-func isAny(sv reflect.Value) bool {
- type wkt interface {
- XXX_WellKnownType() string
- }
- t, ok := sv.Addr().Interface().(wkt)
- return ok && t.XXX_WellKnownType() == "Any"
-}
-
-// writeProto3Any writes an expanded google.protobuf.Any message.
-//
-// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
-// required messages are not linked in).
-//
-// It returns (true, error) when sv was written in expanded format or an error
-// was encountered.
-func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
- turl := sv.FieldByName("TypeUrl")
- val := sv.FieldByName("Value")
- if !turl.IsValid() || !val.IsValid() {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- b, ok := val.Interface().([]byte)
- if !ok {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- parts := strings.Split(turl.String(), "/")
- mt := MessageType(parts[len(parts)-1])
- if mt == nil {
- return false, nil
- }
- m := reflect.New(mt.Elem())
- if err := Unmarshal(b, m.Interface().(Message)); err != nil {
- return false, nil
- }
- w.Write([]byte("["))
- u := turl.String()
- if requiresQuotes(u) {
- writeString(w, u)
- } else {
- w.Write([]byte(u))
- }
- if w.compact {
- w.Write([]byte("]:<"))
- } else {
- w.Write([]byte("]: <\n"))
- w.ind++
- }
- if err := tm.writeStruct(w, m.Elem()); err != nil {
- return true, err
- }
- if w.compact {
- w.Write([]byte("> "))
- } else {
- w.ind--
- w.Write([]byte(">\n"))
- }
- return true, nil
-}
-
-func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
- if tm.ExpandAny && isAny(sv) {
- if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
- return err
- }
- }
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < sv.NumField(); i++ {
- fv := sv.Field(i)
- props := sprops.Prop[i]
- name := st.Field(i).Name
-
- if name == "XXX_NoUnkeyedLiteral" {
- continue
- }
-
- if strings.HasPrefix(name, "XXX_") {
- // There are two XXX_ fields:
- // XXX_unrecognized []byte
- // XXX_extensions map[int32]proto.Extension
- // The first is handled here;
- // the second is handled at the bottom of this function.
- if name == "XXX_unrecognized" && !fv.IsNil() {
- if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Field not filled in. This could be an optional field or
- // a required field that wasn't filled in. Either way, there
- // isn't anything we can show for it.
- continue
- }
- if fv.Kind() == reflect.Slice && fv.IsNil() {
- // Repeated field that is empty, or a bytes field that is unused.
- continue
- }
-
- if props.Repeated && fv.Kind() == reflect.Slice {
- // Repeated field.
- for j := 0; j < fv.Len(); j++ {
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- v := fv.Index(j)
- if v.Kind() == reflect.Ptr && v.IsNil() {
- // A nil message in a repeated field is not valid,
- // but we can handle that more gracefully than panicking.
- if _, err := w.Write([]byte("\n")); err != nil {
- return err
- }
- continue
- }
- if err := tm.writeAny(w, v, props); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Map {
- // Map fields are rendered as a repeated struct with key/value fields.
- keys := fv.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := fv.MapIndex(key)
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- // open struct
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- // key
- if _, err := w.WriteString("key:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, key, props.MapKeyProp); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- // nil values aren't legal, but we can avoid panicking because of them.
- if val.Kind() != reflect.Ptr || !val.IsNil() {
- // value
- if _, err := w.WriteString("value:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, val, props.MapValProp); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- // close struct
- w.unindent()
- if err := w.WriteByte('>'); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
- // empty bytes field
- continue
- }
- if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
- // proto3 non-repeated scalar field; skip if zero value
- if isProto3Zero(fv) {
- continue
- }
- }
-
- if fv.Kind() == reflect.Interface {
- // Check if it is a oneof.
- if st.Field(i).Tag.Get("protobuf_oneof") != "" {
- // fv is nil, or holds a pointer to generated struct.
- // That generated struct has exactly one field,
- // which has a protobuf struct tag.
- if fv.IsNil() {
- continue
- }
- inner := fv.Elem().Elem() // interface -> *T -> T
- tag := inner.Type().Field(0).Tag.Get("protobuf")
- props = new(Properties) // Overwrite the outer props var, but not its pointee.
- props.Parse(tag)
- // Write the value in the oneof, not the oneof itself.
- fv = inner.Field(0)
-
- // Special case to cope with malformed messages gracefully:
- // If the value in the oneof is a nil pointer, don't panic
- // in writeAny.
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Use errors.New so writeAny won't render quotes.
- msg := errors.New("/* nil */")
- fv = reflect.ValueOf(&msg).Elem()
- }
- }
- }
-
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
-
- // Enums have a String method, so writeAny will work fine.
- if err := tm.writeAny(w, fv, props); err != nil {
- return err
- }
-
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
-
- // Extensions (the XXX_extensions field).
- pv := sv.Addr()
- if _, err := extendable(pv.Interface()); err == nil {
- if err := tm.writeExtensions(w, pv); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// writeAny writes an arbitrary field.
-func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
- v = reflect.Indirect(v)
-
- // Floats have special cases.
- if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
- x := v.Float()
- var b []byte
- switch {
- case math.IsInf(x, 1):
- b = posInf
- case math.IsInf(x, -1):
- b = negInf
- case math.IsNaN(x):
- b = nan
- }
- if b != nil {
- _, err := w.Write(b)
- return err
- }
- // Other values are handled below.
- }
-
- // We don't attempt to serialise every possible value type; only those
- // that can occur in protocol buffers.
- switch v.Kind() {
- case reflect.Slice:
- // Should only be a []byte; repeated fields are handled in writeStruct.
- if err := writeString(w, string(v.Bytes())); err != nil {
- return err
- }
- case reflect.String:
- if err := writeString(w, v.String()); err != nil {
- return err
- }
- case reflect.Struct:
- // Required/optional group/message.
- var bra, ket byte = '<', '>'
- if props != nil && props.Wire == "group" {
- bra, ket = '{', '}'
- }
- if err := w.WriteByte(bra); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- if v.CanAddr() {
- // Calling v.Interface on a struct causes the reflect package to
- // copy the entire struct. This is racy with the new Marshaler
- // since we atomically update the XXX_sizecache.
- //
- // Thus, we retrieve a pointer to the struct if possible to avoid
- // a race since v.Interface on the pointer doesn't copy the struct.
- //
- // If v is not addressable, then we are not worried about a race
- // since it implies that the binary Marshaler cannot possibly be
- // mutating this value.
- v = v.Addr()
- }
- if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = w.Write(text); err != nil {
- return err
- }
- } else {
- if v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- if err := tm.writeStruct(w, v); err != nil {
- return err
- }
- }
- w.unindent()
- if err := w.WriteByte(ket); err != nil {
- return err
- }
- default:
- _, err := fmt.Fprint(w, v.Interface())
- return err
- }
- return nil
-}
-
-// equivalent to C's isprint.
-func isprint(c byte) bool {
- return c >= 0x20 && c < 0x7f
-}
-
-// writeString writes a string in the protocol buffer text format.
-// It is similar to strconv.Quote except we don't use Go escape sequences,
-// we treat the string as a byte sequence, and we use octal escapes.
-// These differences are to maintain interoperability with the other
-// languages' implementations of the text format.
-func writeString(w *textWriter, s string) error {
- // use WriteByte here to get any needed indent
- if err := w.WriteByte('"'); err != nil {
- return err
- }
- // Loop over the bytes, not the runes.
- for i := 0; i < len(s); i++ {
- var err error
- // Divergence from C++: we don't escape apostrophes.
- // There's no need to escape them, and the C++ parser
- // copes with a naked apostrophe.
- switch c := s[i]; c {
- case '\n':
- _, err = w.w.Write(backslashN)
- case '\r':
- _, err = w.w.Write(backslashR)
- case '\t':
- _, err = w.w.Write(backslashT)
- case '"':
- _, err = w.w.Write(backslashDQ)
- case '\\':
- _, err = w.w.Write(backslashBS)
- default:
- if isprint(c) {
- err = w.w.WriteByte(c)
- } else {
- _, err = fmt.Fprintf(w.w, "\\%03o", c)
- }
- }
- if err != nil {
- return err
- }
- }
- return w.WriteByte('"')
-}
-
-func writeUnknownStruct(w *textWriter, data []byte) (err error) {
- if !w.compact {
- if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
- return err
- }
- }
- b := NewBuffer(data)
- for b.index < len(b.buf) {
- x, err := b.DecodeVarint()
- if err != nil {
- _, err := fmt.Fprintf(w, "/* %v */\n", err)
- return err
- }
- wire, tag := x&7, x>>3
- if wire == WireEndGroup {
- w.unindent()
- if _, err := w.Write(endBraceNewline); err != nil {
- return err
- }
- continue
- }
- if _, err := fmt.Fprint(w, tag); err != nil {
- return err
- }
- if wire != WireStartGroup {
- if err := w.WriteByte(':'); err != nil {
- return err
- }
- }
- if !w.compact || wire == WireStartGroup {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- switch wire {
- case WireBytes:
- buf, e := b.DecodeRawBytes(false)
- if e == nil {
- _, err = fmt.Fprintf(w, "%q", buf)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", e)
- }
- case WireFixed32:
- x, err = b.DecodeFixed32()
- err = writeUnknownInt(w, x, err)
- case WireFixed64:
- x, err = b.DecodeFixed64()
- err = writeUnknownInt(w, x, err)
- case WireStartGroup:
- err = w.WriteByte('{')
- w.indent()
- case WireVarint:
- x, err = b.DecodeVarint()
- err = writeUnknownInt(w, x, err)
- default:
- _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
- }
- if err != nil {
- return err
- }
- if err = w.WriteByte('\n'); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeUnknownInt(w *textWriter, x uint64, err error) error {
- if err == nil {
- _, err = fmt.Fprint(w, x)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", err)
- }
- return err
-}
-
-type int32Slice []int32
-
-func (s int32Slice) Len() int { return len(s) }
-func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
-func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-
-// writeExtensions writes all the extensions in pv.
-// pv is assumed to be a pointer to a protocol message struct that is extendable.
-func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
- emap := extensionMaps[pv.Type().Elem()]
- ep, _ := extendable(pv.Interface())
-
- // Order the extensions by ID.
- // This isn't strictly necessary, but it will give us
- // canonical output, which will also make testing easier.
- m, mu := ep.extensionsRead()
- if m == nil {
- return nil
- }
- mu.Lock()
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
- mu.Unlock()
-
- for _, extNum := range ids {
- ext := m[extNum]
- var desc *ExtensionDesc
- if emap != nil {
- desc = emap[extNum]
- }
- if desc == nil {
- // Unknown extension.
- if err := writeUnknownStruct(w, ext.enc); err != nil {
- return err
- }
- continue
- }
-
- pb, err := GetExtension(ep, desc)
- if err != nil {
- return fmt.Errorf("failed getting extension: %v", err)
- }
-
- // Repeated extensions will appear as a slice.
- if !desc.repeated() {
- if err := tm.writeExtension(w, desc.Name, pb); err != nil {
- return err
- }
- } else {
- v := reflect.ValueOf(pb)
- for i := 0; i < v.Len(); i++ {
- if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
- if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- return nil
-}
-
-func (w *textWriter) writeIndent() {
- if !w.complete {
- return
- }
- remain := w.ind * 2
- for remain > 0 {
- n := remain
- if n > len(spaces) {
- n = len(spaces)
- }
- w.w.Write(spaces[:n])
- remain -= n
- }
- w.complete = false
-}
-
-// TextMarshaler is a configurable text format marshaler.
-type TextMarshaler struct {
- Compact bool // use compact text format (one line).
- ExpandAny bool // expand google.protobuf.Any messages of known types
-}
-
-// Marshal writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
- val := reflect.ValueOf(pb)
- if pb == nil || val.IsNil() {
- w.Write([]byte(""))
- return nil
- }
- var bw *bufio.Writer
- ww, ok := w.(writer)
- if !ok {
- bw = bufio.NewWriter(w)
- ww = bw
- }
- aw := &textWriter{
- w: ww,
- complete: true,
- compact: tm.Compact,
- }
-
- if etm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = aw.Write(text); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
- }
- // Dereference the received pointer so we don't have outer < and >.
- v := reflect.Indirect(val)
- if err := tm.writeStruct(aw, v); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
-}
-
-// Text is the same as Marshal, but returns the string directly.
-func (tm *TextMarshaler) Text(pb Message) string {
- var buf bytes.Buffer
- tm.Marshal(&buf, pb)
- return buf.String()
-}
-
-var (
- defaultTextMarshaler = TextMarshaler{}
- compactTextMarshaler = TextMarshaler{Compact: true}
-)
-
-// TODO: consider removing some of the Marshal functions below.
-
-// MarshalText writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
-
-// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
-
-// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
-
-// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go
deleted file mode 100644
index bb55a3a..0000000
--- a/vendor/github.com/golang/protobuf/proto/text_parser.go
+++ /dev/null
@@ -1,880 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package proto
-
-// Functions for parsing the Text protocol buffer format.
-// TODO: message sets.
-
-import (
- "encoding"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "unicode/utf8"
-)
-
-// Error string emitted when deserializing Any and fields are already set
-const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
-
-type ParseError struct {
- Message string
- Line int // 1-based line number
- Offset int // 0-based byte offset from start of input
-}
-
-func (p *ParseError) Error() string {
- if p.Line == 1 {
- // show offset only for first line
- return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
- }
- return fmt.Sprintf("line %d: %v", p.Line, p.Message)
-}
-
-type token struct {
- value string
- err *ParseError
- line int // line number
- offset int // byte number from start of input, not start of line
- unquoted string // the unquoted version of value, if it was a quoted string
-}
-
-func (t *token) String() string {
- if t.err == nil {
- return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
- }
- return fmt.Sprintf("parse error: %v", t.err)
-}
-
-type textParser struct {
- s string // remaining input
- done bool // whether the parsing is finished (success or error)
- backed bool // whether back() was called
- offset, line int
- cur token
-}
-
-func newTextParser(s string) *textParser {
- p := new(textParser)
- p.s = s
- p.line = 1
- p.cur.line = 1
- return p
-}
-
-func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
- pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
- p.cur.err = pe
- p.done = true
- return pe
-}
-
-// Numbers and identifiers are matched by [-+._A-Za-z0-9]
-func isIdentOrNumberChar(c byte) bool {
- switch {
- case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
- return true
- case '0' <= c && c <= '9':
- return true
- }
- switch c {
- case '-', '+', '.', '_':
- return true
- }
- return false
-}
-
-func isWhitespace(c byte) bool {
- switch c {
- case ' ', '\t', '\n', '\r':
- return true
- }
- return false
-}
-
-func isQuote(c byte) bool {
- switch c {
- case '"', '\'':
- return true
- }
- return false
-}
-
-func (p *textParser) skipWhitespace() {
- i := 0
- for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
- if p.s[i] == '#' {
- // comment; skip to end of line or input
- for i < len(p.s) && p.s[i] != '\n' {
- i++
- }
- if i == len(p.s) {
- break
- }
- }
- if p.s[i] == '\n' {
- p.line++
- }
- i++
- }
- p.offset += i
- p.s = p.s[i:len(p.s)]
- if len(p.s) == 0 {
- p.done = true
- }
-}
-
-func (p *textParser) advance() {
- // Skip whitespace
- p.skipWhitespace()
- if p.done {
- return
- }
-
- // Start of non-whitespace
- p.cur.err = nil
- p.cur.offset, p.cur.line = p.offset, p.line
- p.cur.unquoted = ""
- switch p.s[0] {
- case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
- // Single symbol
- p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
- case '"', '\'':
- // Quoted string
- i := 1
- for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
- if p.s[i] == '\\' && i+1 < len(p.s) {
- // skip escaped char
- i++
- }
- i++
- }
- if i >= len(p.s) || p.s[i] != p.s[0] {
- p.errorf("unmatched quote")
- return
- }
- unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
- if err != nil {
- p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
- return
- }
- p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
- p.cur.unquoted = unq
- default:
- i := 0
- for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
- i++
- }
- if i == 0 {
- p.errorf("unexpected byte %#x", p.s[0])
- return
- }
- p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
- }
- p.offset += len(p.cur.value)
-}
-
-var (
- errBadUTF8 = errors.New("proto: bad UTF-8")
-)
-
-func unquoteC(s string, quote rune) (string, error) {
- // This is based on C++'s tokenizer.cc.
- // Despite its name, this is *not* parsing C syntax.
- // For instance, "\0" is an invalid quoted string.
-
- // Avoid allocation in trivial cases.
- simple := true
- for _, r := range s {
- if r == '\\' || r == quote {
- simple = false
- break
- }
- }
- if simple {
- return s, nil
- }
-
- buf := make([]byte, 0, 3*len(s)/2)
- for len(s) > 0 {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", errBadUTF8
- }
- s = s[n:]
- if r != '\\' {
- if r < utf8.RuneSelf {
- buf = append(buf, byte(r))
- } else {
- buf = append(buf, string(r)...)
- }
- continue
- }
-
- ch, tail, err := unescape(s)
- if err != nil {
- return "", err
- }
- buf = append(buf, ch...)
- s = tail
- }
- return string(buf), nil
-}
-
-func unescape(s string) (ch string, tail string, err error) {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", "", errBadUTF8
- }
- s = s[n:]
- switch r {
- case 'a':
- return "\a", s, nil
- case 'b':
- return "\b", s, nil
- case 'f':
- return "\f", s, nil
- case 'n':
- return "\n", s, nil
- case 'r':
- return "\r", s, nil
- case 't':
- return "\t", s, nil
- case 'v':
- return "\v", s, nil
- case '?':
- return "?", s, nil // trigraph workaround
- case '\'', '"', '\\':
- return string(r), s, nil
- case '0', '1', '2', '3', '4', '5', '6', '7':
- if len(s) < 2 {
- return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
- }
- ss := string(r) + s[:2]
- s = s[2:]
- i, err := strconv.ParseUint(ss, 8, 8)
- if err != nil {
- return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
- }
- return string([]byte{byte(i)}), s, nil
- case 'x', 'X', 'u', 'U':
- var n int
- switch r {
- case 'x', 'X':
- n = 2
- case 'u':
- n = 4
- case 'U':
- n = 8
- }
- if len(s) < n {
- return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
- }
- ss := s[:n]
- s = s[n:]
- i, err := strconv.ParseUint(ss, 16, 64)
- if err != nil {
- return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
- }
- if r == 'x' || r == 'X' {
- return string([]byte{byte(i)}), s, nil
- }
- if i > utf8.MaxRune {
- return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
- }
- return string(i), s, nil
- }
- return "", "", fmt.Errorf(`unknown escape \%c`, r)
-}
-
-// Back off the parser by one token. Can only be done between calls to next().
-// It makes the next advance() a no-op.
-func (p *textParser) back() { p.backed = true }
-
-// Advances the parser and returns the new current token.
-func (p *textParser) next() *token {
- if p.backed || p.done {
- p.backed = false
- return &p.cur
- }
- p.advance()
- if p.done {
- p.cur.value = ""
- } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
- // Look for multiple quoted strings separated by whitespace,
- // and concatenate them.
- cat := p.cur
- for {
- p.skipWhitespace()
- if p.done || !isQuote(p.s[0]) {
- break
- }
- p.advance()
- if p.cur.err != nil {
- return &p.cur
- }
- cat.value += " " + p.cur.value
- cat.unquoted += p.cur.unquoted
- }
- p.done = false // parser may have seen EOF, but we want to return cat
- p.cur = cat
- }
- return &p.cur
-}
-
-func (p *textParser) consumeToken(s string) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != s {
- p.back()
- return p.errorf("expected %q, found %q", s, tok.value)
- }
- return nil
-}
-
-// Return a RequiredNotSetError indicating which required field was not set.
-func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < st.NumField(); i++ {
- if !isNil(sv.Field(i)) {
- continue
- }
-
- props := sprops.Prop[i]
- if props.Required {
- return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
- }
- }
- return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen
-}
-
-// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
- i, ok := sprops.decoderOrigNames[name]
- if ok {
- return i, sprops.Prop[i], true
- }
- return -1, nil, false
-}
-
-// Consume a ':' from the input stream (if the next token is a colon),
-// returning an error if a colon is needed but not present.
-func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ":" {
- // Colon is optional when the field is a group or message.
- needColon := true
- switch props.Wire {
- case "group":
- needColon = false
- case "bytes":
- // A "bytes" field is either a message, a string, or a repeated field;
- // those three become *T, *string and []T respectively, so we can check for
- // this field being a pointer to a non-string.
- if typ.Kind() == reflect.Ptr {
- // *T or *string
- if typ.Elem().Kind() == reflect.String {
- break
- }
- } else if typ.Kind() == reflect.Slice {
- // []T or []*T
- if typ.Elem().Kind() != reflect.Ptr {
- break
- }
- } else if typ.Kind() == reflect.String {
- // The proto3 exception is for a string field,
- // which requires a colon.
- break
- }
- needColon = false
- }
- if needColon {
- return p.errorf("expected ':', found %q", tok.value)
- }
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
- st := sv.Type()
- sprops := GetProperties(st)
- reqCount := sprops.reqCount
- var reqFieldErr error
- fieldSet := make(map[string]bool)
- // A struct is a sequence of "name: value", terminated by one of
- // '>' or '}', or the end of the input. A name may also be
- // "[extension]" or "[type/url]".
- //
- // The whole struct can also be an expanded Any message, like:
- // [type/url] < ... struct contents ... >
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- if tok.value == "[" {
- // Looks like an extension or an Any.
- //
- // TODO: Check whether we need to handle
- // namespace rooted names (e.g. ".something.Foo").
- extName, err := p.consumeExtName()
- if err != nil {
- return err
- }
-
- if s := strings.LastIndex(extName, "/"); s >= 0 {
- // If it contains a slash, it's an Any type URL.
- messageName := extName[s+1:]
- mt := MessageType(messageName)
- if mt == nil {
- return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
- }
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- // consume an optional colon
- if tok.value == ":" {
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- }
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- v := reflect.New(mt.Elem())
- if pe := p.readStruct(v.Elem(), terminator); pe != nil {
- return pe
- }
- b, err := Marshal(v.Interface().(Message))
- if err != nil {
- return p.errorf("failed to marshal message of type %q: %v", messageName, err)
- }
- if fieldSet["type_url"] {
- return p.errorf(anyRepeatedlyUnpacked, "type_url")
- }
- if fieldSet["value"] {
- return p.errorf(anyRepeatedlyUnpacked, "value")
- }
- sv.FieldByName("TypeUrl").SetString(extName)
- sv.FieldByName("Value").SetBytes(b)
- fieldSet["type_url"] = true
- fieldSet["value"] = true
- continue
- }
-
- var desc *ExtensionDesc
- // This could be faster, but it's functional.
- // TODO: Do something smarter than a linear scan.
- for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
- if d.Name == extName {
- desc = d
- break
- }
- }
- if desc == nil {
- return p.errorf("unrecognized extension %q", extName)
- }
-
- props := &Properties{}
- props.Parse(desc.Tag)
-
- typ := reflect.TypeOf(desc.ExtensionType)
- if err := p.checkForColon(props, typ); err != nil {
- return err
- }
-
- rep := desc.repeated()
-
- // Read the extension structure, and set it in
- // the value we're constructing.
- var ext reflect.Value
- if !rep {
- ext = reflect.New(typ).Elem()
- } else {
- ext = reflect.New(typ.Elem()).Elem()
- }
- if err := p.readAny(ext, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- ep := sv.Addr().Interface().(Message)
- if !rep {
- SetExtension(ep, desc, ext.Interface())
- } else {
- old, err := GetExtension(ep, desc)
- var sl reflect.Value
- if err == nil {
- sl = reflect.ValueOf(old) // existing slice
- } else {
- sl = reflect.MakeSlice(typ, 0, 1)
- }
- sl = reflect.Append(sl, ext)
- SetExtension(ep, desc, sl.Interface())
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- continue
- }
-
- // This is a normal, non-extension field.
- name := tok.value
- var dst reflect.Value
- fi, props, ok := structFieldByName(sprops, name)
- if ok {
- dst = sv.Field(fi)
- } else if oop, ok := sprops.OneofTypes[name]; ok {
- // It is a oneof.
- props = oop.Prop
- nv := reflect.New(oop.Type.Elem())
- dst = nv.Elem().Field(0)
- field := sv.Field(oop.Field)
- if !field.IsNil() {
- return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
- }
- field.Set(nv)
- }
- if !dst.IsValid() {
- return p.errorf("unknown field name %q in %v", name, st)
- }
-
- if dst.Kind() == reflect.Map {
- // Consume any colon.
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Construct the map if it doesn't already exist.
- if dst.IsNil() {
- dst.Set(reflect.MakeMap(dst.Type()))
- }
- key := reflect.New(dst.Type().Key()).Elem()
- val := reflect.New(dst.Type().Elem()).Elem()
-
- // The map entry should be this sequence of tokens:
- // < key : KEY value : VALUE >
- // However, implementations may omit key or value, and technically
- // we should support them in any order. See b/28924776 for a time
- // this went wrong.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- switch tok.value {
- case "key":
- if err := p.consumeToken(":"); err != nil {
- return err
- }
- if err := p.readAny(key, props.MapKeyProp); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- case "value":
- if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil {
- return err
- }
- if err := p.readAny(val, props.MapValProp); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- default:
- p.back()
- return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
- }
- }
-
- dst.SetMapIndex(key, val)
- continue
- }
-
- // Check that it's not already set if it's not a repeated field.
- if !props.Repeated && fieldSet[name] {
- return p.errorf("non-repeated field %q was repeated", name)
- }
-
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Parse into the field.
- fieldSet[name] = true
- if err := p.readAny(dst, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- if props.Required {
- reqCount--
- }
-
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
-
- }
-
- if reqCount > 0 {
- return p.missingRequiredFieldError(sv)
- }
- return reqFieldErr
-}
-
-// consumeExtName consumes extension name or expanded Any type URL and the
-// following ']'. It returns the name or URL consumed.
-func (p *textParser) consumeExtName() (string, error) {
- tok := p.next()
- if tok.err != nil {
- return "", tok.err
- }
-
- // If extension name or type url is quoted, it's a single token.
- if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
- name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
- if err != nil {
- return "", err
- }
- return name, p.consumeToken("]")
- }
-
- // Consume everything up to "]"
- var parts []string
- for tok.value != "]" {
- parts = append(parts, tok.value)
- tok = p.next()
- if tok.err != nil {
- return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
- }
- if p.done && tok.value != "]" {
- return "", p.errorf("unclosed type_url or extension name")
- }
- }
- return strings.Join(parts, ""), nil
-}
-
-// consumeOptionalSeparator consumes an optional semicolon or comma.
-// It is used in readStruct to provide backward compatibility.
-func (p *textParser) consumeOptionalSeparator() error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ";" && tok.value != "," {
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readAny(v reflect.Value, props *Properties) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "" {
- return p.errorf("unexpected EOF")
- }
-
- switch fv := v; fv.Kind() {
- case reflect.Slice:
- at := v.Type()
- if at.Elem().Kind() == reflect.Uint8 {
- // Special case for []byte
- if tok.value[0] != '"' && tok.value[0] != '\'' {
- // Deliberately written out here, as the error after
- // this switch statement would write "invalid []byte: ...",
- // which is not as user-friendly.
- return p.errorf("invalid string: %v", tok.value)
- }
- bytes := []byte(tok.unquoted)
- fv.Set(reflect.ValueOf(bytes))
- return nil
- }
- // Repeated field.
- if tok.value == "[" {
- // Repeated field with list notation, like [1,2,3].
- for {
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- err := p.readAny(fv.Index(fv.Len()-1), props)
- if err != nil {
- return err
- }
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "]" {
- break
- }
- if tok.value != "," {
- return p.errorf("Expected ']' or ',' found %q", tok.value)
- }
- }
- return nil
- }
- // One value of the repeated field.
- p.back()
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- return p.readAny(fv.Index(fv.Len()-1), props)
- case reflect.Bool:
- // true/1/t/True or false/f/0/False.
- switch tok.value {
- case "true", "1", "t", "True":
- fv.SetBool(true)
- return nil
- case "false", "0", "f", "False":
- fv.SetBool(false)
- return nil
- }
- case reflect.Float32, reflect.Float64:
- v := tok.value
- // Ignore 'f' for compatibility with output generated by C++, but don't
- // remove 'f' when the value is "-inf" or "inf".
- if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
- v = v[:len(v)-1]
- }
- if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
- fv.SetFloat(f)
- return nil
- }
- case reflect.Int32:
- if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- if len(props.Enum) == 0 {
- break
- }
- m, ok := enumValueMaps[props.Enum]
- if !ok {
- break
- }
- x, ok := m[tok.value]
- if !ok {
- break
- }
- fv.SetInt(int64(x))
- return nil
- case reflect.Int64:
- if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- case reflect.Ptr:
- // A basic field (indirected through pointer), or a repeated message/group
- p.back()
- fv.Set(reflect.New(fv.Type().Elem()))
- return p.readAny(fv.Elem(), props)
- case reflect.String:
- if tok.value[0] == '"' || tok.value[0] == '\'' {
- fv.SetString(tok.unquoted)
- return nil
- }
- case reflect.Struct:
- var terminator string
- switch tok.value {
- case "{":
- terminator = "}"
- case "<":
- terminator = ">"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
- return p.readStruct(fv, terminator)
- case reflect.Uint32:
- if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
- fv.SetUint(uint64(x))
- return nil
- }
- case reflect.Uint64:
- if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
- fv.SetUint(x)
- return nil
- }
- }
- return p.errorf("invalid %v: %v", v.Type(), tok.value)
-}
-
-// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
-// before starting to unmarshal, so any existing data in pb is always removed.
-// If a required field is not set and no other error occurs,
-// UnmarshalText returns *RequiredNotSetError.
-func UnmarshalText(s string, pb Message) error {
- if um, ok := pb.(encoding.TextUnmarshaler); ok {
- return um.UnmarshalText([]byte(s))
- }
- pb.Reset()
- v := reflect.ValueOf(pb)
- return newTextParser(s).readStruct(v.Elem(), "")
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
deleted file mode 100644
index 1ded05b..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
+++ /dev/null
@@ -1,2887 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/descriptor.proto
-
-package descriptor
-
-import (
- fmt "fmt"
- proto "github.com/golang/protobuf/proto"
- math "math"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
-
-type FieldDescriptorProto_Type int32
-
-const (
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
- FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
- FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
- FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
- FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
- FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
- FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
- FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
- // New in version 2.
- FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
- FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
- FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
- FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
- FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
- FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
- FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
-)
-
-var FieldDescriptorProto_Type_name = map[int32]string{
- 1: "TYPE_DOUBLE",
- 2: "TYPE_FLOAT",
- 3: "TYPE_INT64",
- 4: "TYPE_UINT64",
- 5: "TYPE_INT32",
- 6: "TYPE_FIXED64",
- 7: "TYPE_FIXED32",
- 8: "TYPE_BOOL",
- 9: "TYPE_STRING",
- 10: "TYPE_GROUP",
- 11: "TYPE_MESSAGE",
- 12: "TYPE_BYTES",
- 13: "TYPE_UINT32",
- 14: "TYPE_ENUM",
- 15: "TYPE_SFIXED32",
- 16: "TYPE_SFIXED64",
- 17: "TYPE_SINT32",
- 18: "TYPE_SINT64",
-}
-
-var FieldDescriptorProto_Type_value = map[string]int32{
- "TYPE_DOUBLE": 1,
- "TYPE_FLOAT": 2,
- "TYPE_INT64": 3,
- "TYPE_UINT64": 4,
- "TYPE_INT32": 5,
- "TYPE_FIXED64": 6,
- "TYPE_FIXED32": 7,
- "TYPE_BOOL": 8,
- "TYPE_STRING": 9,
- "TYPE_GROUP": 10,
- "TYPE_MESSAGE": 11,
- "TYPE_BYTES": 12,
- "TYPE_UINT32": 13,
- "TYPE_ENUM": 14,
- "TYPE_SFIXED32": 15,
- "TYPE_SFIXED64": 16,
- "TYPE_SINT32": 17,
- "TYPE_SINT64": 18,
-}
-
-func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
- p := new(FieldDescriptorProto_Type)
- *p = x
- return p
-}
-
-func (x FieldDescriptorProto_Type) String() string {
- return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
-}
-
-func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Type(value)
- return nil
-}
-
-func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4, 0}
-}
-
-type FieldDescriptorProto_Label int32
-
-const (
- // 0 is reserved for errors
- FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
- FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
- FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
-)
-
-var FieldDescriptorProto_Label_name = map[int32]string{
- 1: "LABEL_OPTIONAL",
- 2: "LABEL_REQUIRED",
- 3: "LABEL_REPEATED",
-}
-
-var FieldDescriptorProto_Label_value = map[string]int32{
- "LABEL_OPTIONAL": 1,
- "LABEL_REQUIRED": 2,
- "LABEL_REPEATED": 3,
-}
-
-func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
- p := new(FieldDescriptorProto_Label)
- *p = x
- return p
-}
-
-func (x FieldDescriptorProto_Label) String() string {
- return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
-}
-
-func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Label(value)
- return nil
-}
-
-func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4, 1}
-}
-
-// Generated classes can be optimized for speed or code size.
-type FileOptions_OptimizeMode int32
-
-const (
- FileOptions_SPEED FileOptions_OptimizeMode = 1
- // etc.
- FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
- FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
-)
-
-var FileOptions_OptimizeMode_name = map[int32]string{
- 1: "SPEED",
- 2: "CODE_SIZE",
- 3: "LITE_RUNTIME",
-}
-
-var FileOptions_OptimizeMode_value = map[string]int32{
- "SPEED": 1,
- "CODE_SIZE": 2,
- "LITE_RUNTIME": 3,
-}
-
-func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
- p := new(FileOptions_OptimizeMode)
- *p = x
- return p
-}
-
-func (x FileOptions_OptimizeMode) String() string {
- return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
-}
-
-func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
- if err != nil {
- return err
- }
- *x = FileOptions_OptimizeMode(value)
- return nil
-}
-
-func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{10, 0}
-}
-
-type FieldOptions_CType int32
-
-const (
- // Default mode.
- FieldOptions_STRING FieldOptions_CType = 0
- FieldOptions_CORD FieldOptions_CType = 1
- FieldOptions_STRING_PIECE FieldOptions_CType = 2
-)
-
-var FieldOptions_CType_name = map[int32]string{
- 0: "STRING",
- 1: "CORD",
- 2: "STRING_PIECE",
-}
-
-var FieldOptions_CType_value = map[string]int32{
- "STRING": 0,
- "CORD": 1,
- "STRING_PIECE": 2,
-}
-
-func (x FieldOptions_CType) Enum() *FieldOptions_CType {
- p := new(FieldOptions_CType)
- *p = x
- return p
-}
-
-func (x FieldOptions_CType) String() string {
- return proto.EnumName(FieldOptions_CType_name, int32(x))
-}
-
-func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
- if err != nil {
- return err
- }
- *x = FieldOptions_CType(value)
- return nil
-}
-
-func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12, 0}
-}
-
-type FieldOptions_JSType int32
-
-const (
- // Use the default type.
- FieldOptions_JS_NORMAL FieldOptions_JSType = 0
- // Use JavaScript strings.
- FieldOptions_JS_STRING FieldOptions_JSType = 1
- // Use JavaScript numbers.
- FieldOptions_JS_NUMBER FieldOptions_JSType = 2
-)
-
-var FieldOptions_JSType_name = map[int32]string{
- 0: "JS_NORMAL",
- 1: "JS_STRING",
- 2: "JS_NUMBER",
-}
-
-var FieldOptions_JSType_value = map[string]int32{
- "JS_NORMAL": 0,
- "JS_STRING": 1,
- "JS_NUMBER": 2,
-}
-
-func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
- p := new(FieldOptions_JSType)
- *p = x
- return p
-}
-
-func (x FieldOptions_JSType) String() string {
- return proto.EnumName(FieldOptions_JSType_name, int32(x))
-}
-
-func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
- if err != nil {
- return err
- }
- *x = FieldOptions_JSType(value)
- return nil
-}
-
-func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12, 1}
-}
-
-// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
-// or neither? HTTP based RPC implementation may choose GET verb for safe
-// methods, and PUT verb for idempotent methods instead of the default POST.
-type MethodOptions_IdempotencyLevel int32
-
-const (
- MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
- MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
- MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
-)
-
-var MethodOptions_IdempotencyLevel_name = map[int32]string{
- 0: "IDEMPOTENCY_UNKNOWN",
- 1: "NO_SIDE_EFFECTS",
- 2: "IDEMPOTENT",
-}
-
-var MethodOptions_IdempotencyLevel_value = map[string]int32{
- "IDEMPOTENCY_UNKNOWN": 0,
- "NO_SIDE_EFFECTS": 1,
- "IDEMPOTENT": 2,
-}
-
-func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
- p := new(MethodOptions_IdempotencyLevel)
- *p = x
- return p
-}
-
-func (x MethodOptions_IdempotencyLevel) String() string {
- return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
-}
-
-func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
- if err != nil {
- return err
- }
- *x = MethodOptions_IdempotencyLevel(value)
- return nil
-}
-
-func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{17, 0}
-}
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-type FileDescriptorSet struct {
- File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
-func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorSet) ProtoMessage() {}
-func (*FileDescriptorSet) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{0}
-}
-
-func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b)
-}
-func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic)
-}
-func (m *FileDescriptorSet) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorSet.Merge(m, src)
-}
-func (m *FileDescriptorSet) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorSet.Size(m)
-}
-func (m *FileDescriptorSet) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo
-
-func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
- if m != nil {
- return m.File
- }
- return nil
-}
-
-// Describes a complete .proto file.
-type FileDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
- // Names of files imported by this file.
- Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
- // Indexes of the public imported files in the dependency list above.
- PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
- // All top-level definitions in this file.
- MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
- Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
-func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorProto) ProtoMessage() {}
-func (*FileDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{1}
-}
-
-func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b)
-}
-func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *FileDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorProto.Merge(m, src)
-}
-func (m *FileDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorProto.Size(m)
-}
-func (m *FileDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo
-
-func (m *FileDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetPackage() string {
- if m != nil && m.Package != nil {
- return *m.Package
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetDependency() []string {
- if m != nil {
- return m.Dependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetPublicDependency() []int32 {
- if m != nil {
- return m.PublicDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetWeakDependency() []int32 {
- if m != nil {
- return m.WeakDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
- if m != nil {
- return m.MessageType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
- if m != nil {
- return m.Service
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetOptions() *FileOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
- if m != nil {
- return m.SourceCodeInfo
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSyntax() string {
- if m != nil && m.Syntax != nil {
- return *m.Syntax
- }
- return ""
-}
-
-// Describes a message type.
-type DescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
- NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
- OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
- Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
- ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
-func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto) ProtoMessage() {}
-func (*DescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2}
-}
-
-func (m *DescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto.Unmarshal(m, b)
-}
-func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto.Merge(m, src)
-}
-func (m *DescriptorProto) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto.Size(m)
-}
-func (m *DescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo
-
-func (m *DescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
- if m != nil {
- return m.Field
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
- if m != nil {
- return m.NestedType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
- if m != nil {
- return m.ExtensionRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
- if m != nil {
- return m.OneofDecl
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOptions() *MessageOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-type DescriptorProto_ExtensionRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
-func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
-func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2, 0}
-}
-
-func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(m, src)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Range of reserved tag numbers. Reserved tag numbers may not be used by
-// fields or extension ranges in the same message. Reserved ranges may
-// not overlap.
-type DescriptorProto_ReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
-func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ReservedRange) ProtoMessage() {}
-func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2, 1}
-}
-
-func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ReservedRange.Merge(m, src)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m)
-}
-func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-type ExtensionRangeOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} }
-func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) }
-func (*ExtensionRangeOptions) ProtoMessage() {}
-func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{3}
-}
-
-var extRange_ExtensionRangeOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ExtensionRangeOptions
-}
-
-func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b)
-}
-func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic)
-}
-func (m *ExtensionRangeOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ExtensionRangeOptions.Merge(m, src)
-}
-func (m *ExtensionRangeOptions) XXX_Size() int {
- return xxx_messageInfo_ExtensionRangeOptions.Size(m)
-}
-func (m *ExtensionRangeOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo
-
-func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-// Describes a field within a message.
-type FieldDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
- Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
- Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
-func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FieldDescriptorProto) ProtoMessage() {}
-func (*FieldDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4}
-}
-
-func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b)
-}
-func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *FieldDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldDescriptorProto.Merge(m, src)
-}
-func (m *FieldDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FieldDescriptorProto.Size(m)
-}
-func (m *FieldDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo
-
-func (m *FieldDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
-
-func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return FieldDescriptorProto_LABEL_OPTIONAL
-}
-
-func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return FieldDescriptorProto_TYPE_DOUBLE
-}
-
-func (m *FieldDescriptorProto) GetTypeName() string {
- if m != nil && m.TypeName != nil {
- return *m.TypeName
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetExtendee() string {
- if m != nil && m.Extendee != nil {
- return *m.Extendee
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetDefaultValue() string {
- if m != nil && m.DefaultValue != nil {
- return *m.DefaultValue
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetOneofIndex() int32 {
- if m != nil && m.OneofIndex != nil {
- return *m.OneofIndex
- }
- return 0
-}
-
-func (m *FieldDescriptorProto) GetJsonName() string {
- if m != nil && m.JsonName != nil {
- return *m.JsonName
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a oneof.
-type OneofDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
-func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*OneofDescriptorProto) ProtoMessage() {}
-func (*OneofDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{5}
-}
-
-func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b)
-}
-func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *OneofDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofDescriptorProto.Merge(m, src)
-}
-func (m *OneofDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_OneofDescriptorProto.Size(m)
-}
-func (m *OneofDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo
-
-func (m *OneofDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes an enum type.
-type EnumDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
- Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
-func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto) ProtoMessage() {}
-func (*EnumDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{6}
-}
-
-func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *EnumDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto.Merge(m, src)
-}
-func (m *EnumDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto.Size(m)
-}
-func (m *EnumDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-// Range of reserved numeric values. Reserved values may not be used by
-// entries in the same enum. Reserved ranges may not overlap.
-//
-// Note that this is distinct from DescriptorProto.ReservedRange in that it
-// is inclusive such that it can appropriately represent the entire int32
-// domain.
-type EnumDescriptorProto_EnumReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} }
-func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {}
-func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{6, 0}
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(m, src)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-// Describes a value within an enum.
-type EnumValueDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
- Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
-func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumValueDescriptorProto) ProtoMessage() {}
-func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{7}
-}
-
-func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *EnumValueDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueDescriptorProto.Merge(m, src)
-}
-func (m *EnumValueDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumValueDescriptorProto.Size(m)
-}
-func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumValueDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumValueDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
-
-func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a service.
-type ServiceDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
- Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
-func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*ServiceDescriptorProto) ProtoMessage() {}
-func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{8}
-}
-
-func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b)
-}
-func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *ServiceDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceDescriptorProto.Merge(m, src)
-}
-func (m *ServiceDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_ServiceDescriptorProto.Size(m)
-}
-func (m *ServiceDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo
-
-func (m *ServiceDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
- if m != nil {
- return m.Method
- }
- return nil
-}
-
-func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a method of a service.
-type MethodDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
- OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
- Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
- // Identifies if client streams multiple client messages
- ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
- // Identifies if server streams multiple server messages
- ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
-func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*MethodDescriptorProto) ProtoMessage() {}
-func (*MethodDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{9}
-}
-
-func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b)
-}
-func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *MethodDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodDescriptorProto.Merge(m, src)
-}
-func (m *MethodDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_MethodDescriptorProto.Size(m)
-}
-func (m *MethodDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo
-
-const Default_MethodDescriptorProto_ClientStreaming bool = false
-const Default_MethodDescriptorProto_ServerStreaming bool = false
-
-func (m *MethodDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetInputType() string {
- if m != nil && m.InputType != nil {
- return *m.InputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOutputType() string {
- if m != nil && m.OutputType != nil {
- return *m.OutputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *MethodDescriptorProto) GetClientStreaming() bool {
- if m != nil && m.ClientStreaming != nil {
- return *m.ClientStreaming
- }
- return Default_MethodDescriptorProto_ClientStreaming
-}
-
-func (m *MethodDescriptorProto) GetServerStreaming() bool {
- if m != nil && m.ServerStreaming != nil {
- return *m.ServerStreaming
- }
- return Default_MethodDescriptorProto_ServerStreaming
-}
-
-type FileOptions struct {
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
- // This option does nothing.
- JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use.
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
- OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
- JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
- PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
- PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"`
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
- // Namespace for generated classes; defaults to the package.
- CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"`
- // Use this option to change the namespace of php generated metadata classes.
- // Default is empty. When this option is empty, the proto file name will be used
- // for determining the namespace.
- PhpMetadataNamespace *string `protobuf:"bytes,44,opt,name=php_metadata_namespace,json=phpMetadataNamespace" json:"php_metadata_namespace,omitempty"`
- // Use this option to change the package of ruby generated classes. Default
- // is empty. When this option is not set, the package name will be used for
- // determining the ruby package.
- RubyPackage *string `protobuf:"bytes,45,opt,name=ruby_package,json=rubyPackage" json:"ruby_package,omitempty"`
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileOptions) Reset() { *m = FileOptions{} }
-func (m *FileOptions) String() string { return proto.CompactTextString(m) }
-func (*FileOptions) ProtoMessage() {}
-func (*FileOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{10}
-}
-
-var extRange_FileOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FileOptions
-}
-
-func (m *FileOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileOptions.Unmarshal(m, b)
-}
-func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic)
-}
-func (m *FileOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileOptions.Merge(m, src)
-}
-func (m *FileOptions) XXX_Size() int {
- return xxx_messageInfo_FileOptions.Size(m)
-}
-func (m *FileOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FileOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileOptions proto.InternalMessageInfo
-
-const Default_FileOptions_JavaMultipleFiles bool = false
-const Default_FileOptions_JavaStringCheckUtf8 bool = false
-const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
-const Default_FileOptions_CcGenericServices bool = false
-const Default_FileOptions_JavaGenericServices bool = false
-const Default_FileOptions_PyGenericServices bool = false
-const Default_FileOptions_PhpGenericServices bool = false
-const Default_FileOptions_Deprecated bool = false
-const Default_FileOptions_CcEnableArenas bool = false
-
-func (m *FileOptions) GetJavaPackage() string {
- if m != nil && m.JavaPackage != nil {
- return *m.JavaPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaOuterClassname() string {
- if m != nil && m.JavaOuterClassname != nil {
- return *m.JavaOuterClassname
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaMultipleFiles() bool {
- if m != nil && m.JavaMultipleFiles != nil {
- return *m.JavaMultipleFiles
- }
- return Default_FileOptions_JavaMultipleFiles
-}
-
-// Deprecated: Do not use.
-func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
- if m != nil && m.JavaGenerateEqualsAndHash != nil {
- return *m.JavaGenerateEqualsAndHash
- }
- return false
-}
-
-func (m *FileOptions) GetJavaStringCheckUtf8() bool {
- if m != nil && m.JavaStringCheckUtf8 != nil {
- return *m.JavaStringCheckUtf8
- }
- return Default_FileOptions_JavaStringCheckUtf8
-}
-
-func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
- if m != nil && m.OptimizeFor != nil {
- return *m.OptimizeFor
- }
- return Default_FileOptions_OptimizeFor
-}
-
-func (m *FileOptions) GetGoPackage() string {
- if m != nil && m.GoPackage != nil {
- return *m.GoPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetCcGenericServices() bool {
- if m != nil && m.CcGenericServices != nil {
- return *m.CcGenericServices
- }
- return Default_FileOptions_CcGenericServices
-}
-
-func (m *FileOptions) GetJavaGenericServices() bool {
- if m != nil && m.JavaGenericServices != nil {
- return *m.JavaGenericServices
- }
- return Default_FileOptions_JavaGenericServices
-}
-
-func (m *FileOptions) GetPyGenericServices() bool {
- if m != nil && m.PyGenericServices != nil {
- return *m.PyGenericServices
- }
- return Default_FileOptions_PyGenericServices
-}
-
-func (m *FileOptions) GetPhpGenericServices() bool {
- if m != nil && m.PhpGenericServices != nil {
- return *m.PhpGenericServices
- }
- return Default_FileOptions_PhpGenericServices
-}
-
-func (m *FileOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FileOptions_Deprecated
-}
-
-func (m *FileOptions) GetCcEnableArenas() bool {
- if m != nil && m.CcEnableArenas != nil {
- return *m.CcEnableArenas
- }
- return Default_FileOptions_CcEnableArenas
-}
-
-func (m *FileOptions) GetObjcClassPrefix() string {
- if m != nil && m.ObjcClassPrefix != nil {
- return *m.ObjcClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetCsharpNamespace() string {
- if m != nil && m.CsharpNamespace != nil {
- return *m.CsharpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetSwiftPrefix() string {
- if m != nil && m.SwiftPrefix != nil {
- return *m.SwiftPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpClassPrefix() string {
- if m != nil && m.PhpClassPrefix != nil {
- return *m.PhpClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpNamespace() string {
- if m != nil && m.PhpNamespace != nil {
- return *m.PhpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpMetadataNamespace() string {
- if m != nil && m.PhpMetadataNamespace != nil {
- return *m.PhpMetadataNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetRubyPackage() string {
- if m != nil && m.RubyPackage != nil {
- return *m.RubyPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MessageOptions struct {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MessageOptions) Reset() { *m = MessageOptions{} }
-func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
-func (*MessageOptions) ProtoMessage() {}
-func (*MessageOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{11}
-}
-
-var extRange_MessageOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MessageOptions
-}
-
-func (m *MessageOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MessageOptions.Unmarshal(m, b)
-}
-func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic)
-}
-func (m *MessageOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageOptions.Merge(m, src)
-}
-func (m *MessageOptions) XXX_Size() int {
- return xxx_messageInfo_MessageOptions.Size(m)
-}
-func (m *MessageOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MessageOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MessageOptions proto.InternalMessageInfo
-
-const Default_MessageOptions_MessageSetWireFormat bool = false
-const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
-const Default_MessageOptions_Deprecated bool = false
-
-func (m *MessageOptions) GetMessageSetWireFormat() bool {
- if m != nil && m.MessageSetWireFormat != nil {
- return *m.MessageSetWireFormat
- }
- return Default_MessageOptions_MessageSetWireFormat
-}
-
-func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
- if m != nil && m.NoStandardDescriptorAccessor != nil {
- return *m.NoStandardDescriptorAccessor
- }
- return Default_MessageOptions_NoStandardDescriptorAccessor
-}
-
-func (m *MessageOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MessageOptions_Deprecated
-}
-
-func (m *MessageOptions) GetMapEntry() bool {
- if m != nil && m.MapEntry != nil {
- return *m.MapEntry
- }
- return false
-}
-
-func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type FieldOptions struct {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // For Google-internal migration only. Do not use.
- Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FieldOptions) Reset() { *m = FieldOptions{} }
-func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
-func (*FieldOptions) ProtoMessage() {}
-func (*FieldOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12}
-}
-
-var extRange_FieldOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FieldOptions
-}
-
-func (m *FieldOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldOptions.Unmarshal(m, b)
-}
-func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic)
-}
-func (m *FieldOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldOptions.Merge(m, src)
-}
-func (m *FieldOptions) XXX_Size() int {
- return xxx_messageInfo_FieldOptions.Size(m)
-}
-func (m *FieldOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FieldOptions proto.InternalMessageInfo
-
-const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
-const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
-const Default_FieldOptions_Lazy bool = false
-const Default_FieldOptions_Deprecated bool = false
-const Default_FieldOptions_Weak bool = false
-
-func (m *FieldOptions) GetCtype() FieldOptions_CType {
- if m != nil && m.Ctype != nil {
- return *m.Ctype
- }
- return Default_FieldOptions_Ctype
-}
-
-func (m *FieldOptions) GetPacked() bool {
- if m != nil && m.Packed != nil {
- return *m.Packed
- }
- return false
-}
-
-func (m *FieldOptions) GetJstype() FieldOptions_JSType {
- if m != nil && m.Jstype != nil {
- return *m.Jstype
- }
- return Default_FieldOptions_Jstype
-}
-
-func (m *FieldOptions) GetLazy() bool {
- if m != nil && m.Lazy != nil {
- return *m.Lazy
- }
- return Default_FieldOptions_Lazy
-}
-
-func (m *FieldOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FieldOptions_Deprecated
-}
-
-func (m *FieldOptions) GetWeak() bool {
- if m != nil && m.Weak != nil {
- return *m.Weak
- }
- return Default_FieldOptions_Weak
-}
-
-func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type OneofOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OneofOptions) Reset() { *m = OneofOptions{} }
-func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
-func (*OneofOptions) ProtoMessage() {}
-func (*OneofOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{13}
-}
-
-var extRange_OneofOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OneofOptions
-}
-
-func (m *OneofOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofOptions.Unmarshal(m, b)
-}
-func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic)
-}
-func (m *OneofOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofOptions.Merge(m, src)
-}
-func (m *OneofOptions) XXX_Size() int {
- return xxx_messageInfo_OneofOptions.Size(m)
-}
-func (m *OneofOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OneofOptions proto.InternalMessageInfo
-
-func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumOptions struct {
- // Set this option to true to allow mapping different tag names to the same
- // value.
- AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumOptions) Reset() { *m = EnumOptions{} }
-func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumOptions) ProtoMessage() {}
-func (*EnumOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{14}
-}
-
-var extRange_EnumOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumOptions
-}
-
-func (m *EnumOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumOptions.Unmarshal(m, b)
-}
-func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic)
-}
-func (m *EnumOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumOptions.Merge(m, src)
-}
-func (m *EnumOptions) XXX_Size() int {
- return xxx_messageInfo_EnumOptions.Size(m)
-}
-func (m *EnumOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumOptions proto.InternalMessageInfo
-
-const Default_EnumOptions_Deprecated bool = false
-
-func (m *EnumOptions) GetAllowAlias() bool {
- if m != nil && m.AllowAlias != nil {
- return *m.AllowAlias
- }
- return false
-}
-
-func (m *EnumOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumOptions_Deprecated
-}
-
-func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumValueOptions struct {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
-func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumValueOptions) ProtoMessage() {}
-func (*EnumValueOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{15}
-}
-
-var extRange_EnumValueOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumValueOptions
-}
-
-func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b)
-}
-func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic)
-}
-func (m *EnumValueOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueOptions.Merge(m, src)
-}
-func (m *EnumValueOptions) XXX_Size() int {
- return xxx_messageInfo_EnumValueOptions.Size(m)
-}
-func (m *EnumValueOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo
-
-const Default_EnumValueOptions_Deprecated bool = false
-
-func (m *EnumValueOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumValueOptions_Deprecated
-}
-
-func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type ServiceOptions struct {
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
-func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
-func (*ServiceOptions) ProtoMessage() {}
-func (*ServiceOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{16}
-}
-
-var extRange_ServiceOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ServiceOptions
-}
-
-func (m *ServiceOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceOptions.Unmarshal(m, b)
-}
-func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic)
-}
-func (m *ServiceOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceOptions.Merge(m, src)
-}
-func (m *ServiceOptions) XXX_Size() int {
- return xxx_messageInfo_ServiceOptions.Size(m)
-}
-func (m *ServiceOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo
-
-const Default_ServiceOptions_Deprecated bool = false
-
-func (m *ServiceOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_ServiceOptions_Deprecated
-}
-
-func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MethodOptions struct {
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodOptions) Reset() { *m = MethodOptions{} }
-func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
-func (*MethodOptions) ProtoMessage() {}
-func (*MethodOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{17}
-}
-
-var extRange_MethodOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MethodOptions
-}
-
-func (m *MethodOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodOptions.Unmarshal(m, b)
-}
-func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic)
-}
-func (m *MethodOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodOptions.Merge(m, src)
-}
-func (m *MethodOptions) XXX_Size() int {
- return xxx_messageInfo_MethodOptions.Size(m)
-}
-func (m *MethodOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodOptions proto.InternalMessageInfo
-
-const Default_MethodOptions_Deprecated bool = false
-const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
-
-func (m *MethodOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MethodOptions_Deprecated
-}
-
-func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
- if m != nil && m.IdempotencyLevel != nil {
- return *m.IdempotencyLevel
- }
- return Default_MethodOptions_IdempotencyLevel
-}
-
-func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-type UninterpretedOption struct {
- Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
- PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
- NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
- DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
- StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
- AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
-func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption) ProtoMessage() {}
-func (*UninterpretedOption) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{18}
-}
-
-func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b)
-}
-func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic)
-}
-func (m *UninterpretedOption) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption.Merge(m, src)
-}
-func (m *UninterpretedOption) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption.Size(m)
-}
-func (m *UninterpretedOption) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo
-
-func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
- if m != nil {
- return m.Name
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetIdentifierValue() string {
- if m != nil && m.IdentifierValue != nil {
- return *m.IdentifierValue
- }
- return ""
-}
-
-func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
- if m != nil && m.PositiveIntValue != nil {
- return *m.PositiveIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetNegativeIntValue() int64 {
- if m != nil && m.NegativeIntValue != nil {
- return *m.NegativeIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetDoubleValue() float64 {
- if m != nil && m.DoubleValue != nil {
- return *m.DoubleValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetStringValue() []byte {
- if m != nil {
- return m.StringValue
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetAggregateValue() string {
- if m != nil && m.AggregateValue != nil {
- return *m.AggregateValue
- }
- return ""
-}
-
-// The name of the uninterpreted option. Each string represents a segment in
-// a dot-separated name. is_extension is true iff a segment represents an
-// extension (denoted with parentheses in options specs in .proto files).
-// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
-// "foo.(bar.baz).qux".
-type UninterpretedOption_NamePart struct {
- NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
- IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
-func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption_NamePart) ProtoMessage() {}
-func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{18, 0}
-}
-
-func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b)
-}
-func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic)
-}
-func (m *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption_NamePart.Merge(m, src)
-}
-func (m *UninterpretedOption_NamePart) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption_NamePart.Size(m)
-}
-func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo
-
-func (m *UninterpretedOption_NamePart) GetNamePart() string {
- if m != nil && m.NamePart != nil {
- return *m.NamePart
- }
- return ""
-}
-
-func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
- if m != nil && m.IsExtension != nil {
- return *m.IsExtension
- }
- return false
-}
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-type SourceCodeInfo struct {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
-func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo) ProtoMessage() {}
-func (*SourceCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{19}
-}
-
-func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic)
-}
-func (m *SourceCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo.Merge(m, src)
-}
-func (m *SourceCodeInfo) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo.Size(m)
-}
-func (m *SourceCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo
-
-func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
- if m != nil {
- return m.Location
- }
- return nil
-}
-
-type SourceCodeInfo_Location struct {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
- TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
- LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
-func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo_Location) ProtoMessage() {}
-func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{19, 0}
-}
-
-func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic)
-}
-func (m *SourceCodeInfo_Location) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo_Location.Merge(m, src)
-}
-func (m *SourceCodeInfo_Location) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo_Location.Size(m)
-}
-func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo
-
-func (m *SourceCodeInfo_Location) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetSpan() []int32 {
- if m != nil {
- return m.Span
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingComments() string {
- if m != nil && m.LeadingComments != nil {
- return *m.LeadingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetTrailingComments() string {
- if m != nil && m.TrailingComments != nil {
- return *m.TrailingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
- if m != nil {
- return m.LeadingDetachedComments
- }
- return nil
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-type GeneratedCodeInfo struct {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
-func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo) ProtoMessage() {}
-func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{20}
-}
-
-func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic)
-}
-func (m *GeneratedCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo.Merge(m, src)
-}
-func (m *GeneratedCodeInfo) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo.Size(m)
-}
-func (m *GeneratedCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
- if m != nil {
- return m.Annotation
- }
- return nil
-}
-
-type GeneratedCodeInfo_Annotation struct {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Identifies the filesystem path to the original source .proto.
- SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
-func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
-func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{20, 0}
-}
-
-func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(m, src)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
- if m != nil && m.SourceFile != nil {
- return *m.SourceFile
- }
- return ""
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
- if m != nil && m.Begin != nil {
- return *m.Begin
- }
- return 0
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func init() {
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
- proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
- proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
- proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
- proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
- proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
- proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
- proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
- proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions")
- proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
- proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange")
- proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
- proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
- proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
- proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
- proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
- proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
- proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
- proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
- proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
- proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
- proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
- proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
- proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
- proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
- proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
- proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
- proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
-}
-
-func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_e5baabe45344a177) }
-
-var fileDescriptor_e5baabe45344a177 = []byte{
- // 2589 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x8e, 0xdb, 0xc6,
- 0x15, 0x0e, 0xf5, 0xb7, 0xd2, 0x91, 0x56, 0x3b, 0x3b, 0xbb, 0xb1, 0xe9, 0xcd, 0x8f, 0xd7, 0xca,
- 0x8f, 0xd7, 0x4e, 0xac, 0x0d, 0x1c, 0xdb, 0x71, 0xd6, 0x45, 0x5a, 0xad, 0x44, 0x6f, 0xe4, 0xee,
- 0x4a, 0x2a, 0xa5, 0x6d, 0x7e, 0x80, 0x82, 0x98, 0x25, 0x47, 0x12, 0x6d, 0x8a, 0x64, 0x48, 0xca,
- 0xf6, 0x06, 0xbd, 0x30, 0xd0, 0xab, 0x5e, 0x15, 0xe8, 0x55, 0x51, 0x14, 0xbd, 0xe8, 0x4d, 0x80,
- 0x3e, 0x40, 0x81, 0xde, 0xf5, 0x09, 0x0a, 0xe4, 0x0d, 0x8a, 0xb6, 0x40, 0xfb, 0x08, 0xbd, 0x2c,
- 0x66, 0x86, 0xa4, 0x48, 0x49, 0x1b, 0x6f, 0x02, 0xc4, 0xb9, 0x92, 0xe6, 0x3b, 0xdf, 0x39, 0x73,
- 0xe6, 0xcc, 0x99, 0x99, 0x33, 0x43, 0xd8, 0x1e, 0x39, 0xce, 0xc8, 0xa2, 0xbb, 0xae, 0xe7, 0x04,
- 0xce, 0xc9, 0x74, 0xb8, 0x6b, 0x50, 0x5f, 0xf7, 0x4c, 0x37, 0x70, 0xbc, 0x3a, 0xc7, 0xf0, 0x9a,
- 0x60, 0xd4, 0x23, 0x46, 0xed, 0x08, 0xd6, 0xef, 0x9b, 0x16, 0x6d, 0xc5, 0xc4, 0x3e, 0x0d, 0xf0,
- 0x5d, 0xc8, 0x0d, 0x4d, 0x8b, 0xca, 0xd2, 0x76, 0x76, 0xa7, 0x7c, 0xf3, 0xcd, 0xfa, 0x9c, 0x52,
- 0x3d, 0xad, 0xd1, 0x63, 0xb0, 0xca, 0x35, 0x6a, 0xff, 0xce, 0xc1, 0xc6, 0x12, 0x29, 0xc6, 0x90,
- 0xb3, 0xc9, 0x84, 0x59, 0x94, 0x76, 0x4a, 0x2a, 0xff, 0x8f, 0x65, 0x58, 0x71, 0x89, 0xfe, 0x88,
- 0x8c, 0xa8, 0x9c, 0xe1, 0x70, 0xd4, 0xc4, 0xaf, 0x03, 0x18, 0xd4, 0xa5, 0xb6, 0x41, 0x6d, 0xfd,
- 0x54, 0xce, 0x6e, 0x67, 0x77, 0x4a, 0x6a, 0x02, 0xc1, 0xef, 0xc0, 0xba, 0x3b, 0x3d, 0xb1, 0x4c,
- 0x5d, 0x4b, 0xd0, 0x60, 0x3b, 0xbb, 0x93, 0x57, 0x91, 0x10, 0xb4, 0x66, 0xe4, 0xab, 0xb0, 0xf6,
- 0x84, 0x92, 0x47, 0x49, 0x6a, 0x99, 0x53, 0xab, 0x0c, 0x4e, 0x10, 0x9b, 0x50, 0x99, 0x50, 0xdf,
- 0x27, 0x23, 0xaa, 0x05, 0xa7, 0x2e, 0x95, 0x73, 0x7c, 0xf4, 0xdb, 0x0b, 0xa3, 0x9f, 0x1f, 0x79,
- 0x39, 0xd4, 0x1a, 0x9c, 0xba, 0x14, 0x37, 0xa0, 0x44, 0xed, 0xe9, 0x44, 0x58, 0xc8, 0x9f, 0x11,
- 0x3f, 0xc5, 0x9e, 0x4e, 0xe6, 0xad, 0x14, 0x99, 0x5a, 0x68, 0x62, 0xc5, 0xa7, 0xde, 0x63, 0x53,
- 0xa7, 0x72, 0x81, 0x1b, 0xb8, 0xba, 0x60, 0xa0, 0x2f, 0xe4, 0xf3, 0x36, 0x22, 0x3d, 0xdc, 0x84,
- 0x12, 0x7d, 0x1a, 0x50, 0xdb, 0x37, 0x1d, 0x5b, 0x5e, 0xe1, 0x46, 0xde, 0x5a, 0x32, 0x8b, 0xd4,
- 0x32, 0xe6, 0x4d, 0xcc, 0xf4, 0xf0, 0x1d, 0x58, 0x71, 0xdc, 0xc0, 0x74, 0x6c, 0x5f, 0x2e, 0x6e,
- 0x4b, 0x3b, 0xe5, 0x9b, 0xaf, 0x2e, 0x4d, 0x84, 0xae, 0xe0, 0xa8, 0x11, 0x19, 0xb7, 0x01, 0xf9,
- 0xce, 0xd4, 0xd3, 0xa9, 0xa6, 0x3b, 0x06, 0xd5, 0x4c, 0x7b, 0xe8, 0xc8, 0x25, 0x6e, 0xe0, 0xf2,
- 0xe2, 0x40, 0x38, 0xb1, 0xe9, 0x18, 0xb4, 0x6d, 0x0f, 0x1d, 0xb5, 0xea, 0xa7, 0xda, 0xf8, 0x02,
- 0x14, 0xfc, 0x53, 0x3b, 0x20, 0x4f, 0xe5, 0x0a, 0xcf, 0x90, 0xb0, 0x55, 0xfb, 0x6b, 0x01, 0xd6,
- 0xce, 0x93, 0x62, 0xf7, 0x20, 0x3f, 0x64, 0xa3, 0x94, 0x33, 0xdf, 0x26, 0x06, 0x42, 0x27, 0x1d,
- 0xc4, 0xc2, 0x77, 0x0c, 0x62, 0x03, 0xca, 0x36, 0xf5, 0x03, 0x6a, 0x88, 0x8c, 0xc8, 0x9e, 0x33,
- 0xa7, 0x40, 0x28, 0x2d, 0xa6, 0x54, 0xee, 0x3b, 0xa5, 0xd4, 0xa7, 0xb0, 0x16, 0xbb, 0xa4, 0x79,
- 0xc4, 0x1e, 0x45, 0xb9, 0xb9, 0xfb, 0x3c, 0x4f, 0xea, 0x4a, 0xa4, 0xa7, 0x32, 0x35, 0xb5, 0x4a,
- 0x53, 0x6d, 0xdc, 0x02, 0x70, 0x6c, 0xea, 0x0c, 0x35, 0x83, 0xea, 0x96, 0x5c, 0x3c, 0x23, 0x4a,
- 0x5d, 0x46, 0x59, 0x88, 0x92, 0x23, 0x50, 0xdd, 0xc2, 0x1f, 0xce, 0x52, 0x6d, 0xe5, 0x8c, 0x4c,
- 0x39, 0x12, 0x8b, 0x6c, 0x21, 0xdb, 0x8e, 0xa1, 0xea, 0x51, 0x96, 0xf7, 0xd4, 0x08, 0x47, 0x56,
- 0xe2, 0x4e, 0xd4, 0x9f, 0x3b, 0x32, 0x35, 0x54, 0x13, 0x03, 0x5b, 0xf5, 0x92, 0x4d, 0xfc, 0x06,
- 0xc4, 0x80, 0xc6, 0xd3, 0x0a, 0xf8, 0x2e, 0x54, 0x89, 0xc0, 0x0e, 0x99, 0xd0, 0xad, 0x2f, 0xa1,
- 0x9a, 0x0e, 0x0f, 0xde, 0x84, 0xbc, 0x1f, 0x10, 0x2f, 0xe0, 0x59, 0x98, 0x57, 0x45, 0x03, 0x23,
- 0xc8, 0x52, 0xdb, 0xe0, 0xbb, 0x5c, 0x5e, 0x65, 0x7f, 0xf1, 0x4f, 0x66, 0x03, 0xce, 0xf2, 0x01,
- 0xbf, 0xbd, 0x38, 0xa3, 0x29, 0xcb, 0xf3, 0xe3, 0xde, 0xfa, 0x00, 0x56, 0x53, 0x03, 0x38, 0x6f,
- 0xd7, 0xb5, 0x5f, 0xc2, 0xcb, 0x4b, 0x4d, 0xe3, 0x4f, 0x61, 0x73, 0x6a, 0x9b, 0x76, 0x40, 0x3d,
- 0xd7, 0xa3, 0x2c, 0x63, 0x45, 0x57, 0xf2, 0x7f, 0x56, 0xce, 0xc8, 0xb9, 0xe3, 0x24, 0x5b, 0x58,
- 0x51, 0x37, 0xa6, 0x8b, 0xe0, 0xf5, 0x52, 0xf1, 0xbf, 0x2b, 0xe8, 0xd9, 0xb3, 0x67, 0xcf, 0x32,
- 0xb5, 0xdf, 0x15, 0x60, 0x73, 0xd9, 0x9a, 0x59, 0xba, 0x7c, 0x2f, 0x40, 0xc1, 0x9e, 0x4e, 0x4e,
- 0xa8, 0xc7, 0x83, 0x94, 0x57, 0xc3, 0x16, 0x6e, 0x40, 0xde, 0x22, 0x27, 0xd4, 0x92, 0x73, 0xdb,
- 0xd2, 0x4e, 0xf5, 0xe6, 0x3b, 0xe7, 0x5a, 0x95, 0xf5, 0x43, 0xa6, 0xa2, 0x0a, 0x4d, 0xfc, 0x11,
- 0xe4, 0xc2, 0x2d, 0x9a, 0x59, 0xb8, 0x7e, 0x3e, 0x0b, 0x6c, 0x2d, 0xa9, 0x5c, 0x0f, 0xbf, 0x02,
- 0x25, 0xf6, 0x2b, 0x72, 0xa3, 0xc0, 0x7d, 0x2e, 0x32, 0x80, 0xe5, 0x05, 0xde, 0x82, 0x22, 0x5f,
- 0x26, 0x06, 0x8d, 0x8e, 0xb6, 0xb8, 0xcd, 0x12, 0xcb, 0xa0, 0x43, 0x32, 0xb5, 0x02, 0xed, 0x31,
- 0xb1, 0xa6, 0x94, 0x27, 0x7c, 0x49, 0xad, 0x84, 0xe0, 0xcf, 0x19, 0x86, 0x2f, 0x43, 0x59, 0xac,
- 0x2a, 0xd3, 0x36, 0xe8, 0x53, 0xbe, 0x7b, 0xe6, 0x55, 0xb1, 0xd0, 0xda, 0x0c, 0x61, 0xdd, 0x3f,
- 0xf4, 0x1d, 0x3b, 0x4a, 0x4d, 0xde, 0x05, 0x03, 0x78, 0xf7, 0x1f, 0xcc, 0x6f, 0xdc, 0xaf, 0x2d,
- 0x1f, 0xde, 0x7c, 0x4e, 0xd5, 0xfe, 0x92, 0x81, 0x1c, 0xdf, 0x2f, 0xd6, 0xa0, 0x3c, 0xf8, 0xac,
- 0xa7, 0x68, 0xad, 0xee, 0xf1, 0xfe, 0xa1, 0x82, 0x24, 0x5c, 0x05, 0xe0, 0xc0, 0xfd, 0xc3, 0x6e,
- 0x63, 0x80, 0x32, 0x71, 0xbb, 0xdd, 0x19, 0xdc, 0xb9, 0x85, 0xb2, 0xb1, 0xc2, 0xb1, 0x00, 0x72,
- 0x49, 0xc2, 0xfb, 0x37, 0x51, 0x1e, 0x23, 0xa8, 0x08, 0x03, 0xed, 0x4f, 0x95, 0xd6, 0x9d, 0x5b,
- 0xa8, 0x90, 0x46, 0xde, 0xbf, 0x89, 0x56, 0xf0, 0x2a, 0x94, 0x38, 0xb2, 0xdf, 0xed, 0x1e, 0xa2,
- 0x62, 0x6c, 0xb3, 0x3f, 0x50, 0xdb, 0x9d, 0x03, 0x54, 0x8a, 0x6d, 0x1e, 0xa8, 0xdd, 0xe3, 0x1e,
- 0x82, 0xd8, 0xc2, 0x91, 0xd2, 0xef, 0x37, 0x0e, 0x14, 0x54, 0x8e, 0x19, 0xfb, 0x9f, 0x0d, 0x94,
- 0x3e, 0xaa, 0xa4, 0xdc, 0x7a, 0xff, 0x26, 0x5a, 0x8d, 0xbb, 0x50, 0x3a, 0xc7, 0x47, 0xa8, 0x8a,
- 0xd7, 0x61, 0x55, 0x74, 0x11, 0x39, 0xb1, 0x36, 0x07, 0xdd, 0xb9, 0x85, 0xd0, 0xcc, 0x11, 0x61,
- 0x65, 0x3d, 0x05, 0xdc, 0xb9, 0x85, 0x70, 0xad, 0x09, 0x79, 0x9e, 0x5d, 0x18, 0x43, 0xf5, 0xb0,
- 0xb1, 0xaf, 0x1c, 0x6a, 0xdd, 0xde, 0xa0, 0xdd, 0xed, 0x34, 0x0e, 0x91, 0x34, 0xc3, 0x54, 0xe5,
- 0x67, 0xc7, 0x6d, 0x55, 0x69, 0xa1, 0x4c, 0x12, 0xeb, 0x29, 0x8d, 0x81, 0xd2, 0x42, 0xd9, 0x9a,
- 0x0e, 0x9b, 0xcb, 0xf6, 0xc9, 0xa5, 0x2b, 0x23, 0x31, 0xc5, 0x99, 0x33, 0xa6, 0x98, 0xdb, 0x5a,
- 0x98, 0xe2, 0x7f, 0x65, 0x60, 0x63, 0xc9, 0x59, 0xb1, 0xb4, 0x93, 0x1f, 0x43, 0x5e, 0xa4, 0xa8,
- 0x38, 0x3d, 0xaf, 0x2d, 0x3d, 0x74, 0x78, 0xc2, 0x2e, 0x9c, 0xa0, 0x5c, 0x2f, 0x59, 0x41, 0x64,
- 0xcf, 0xa8, 0x20, 0x98, 0x89, 0x85, 0x3d, 0xfd, 0x17, 0x0b, 0x7b, 0xba, 0x38, 0xf6, 0xee, 0x9c,
- 0xe7, 0xd8, 0xe3, 0xd8, 0xb7, 0xdb, 0xdb, 0xf3, 0x4b, 0xf6, 0xf6, 0x7b, 0xb0, 0xbe, 0x60, 0xe8,
- 0xdc, 0x7b, 0xec, 0xaf, 0x24, 0x90, 0xcf, 0x0a, 0xce, 0x73, 0x76, 0xba, 0x4c, 0x6a, 0xa7, 0xbb,
- 0x37, 0x1f, 0xc1, 0x2b, 0x67, 0x4f, 0xc2, 0xc2, 0x5c, 0x7f, 0x25, 0xc1, 0x85, 0xe5, 0x95, 0xe2,
- 0x52, 0x1f, 0x3e, 0x82, 0xc2, 0x84, 0x06, 0x63, 0x27, 0xaa, 0x96, 0xde, 0x5e, 0x72, 0x06, 0x33,
- 0xf1, 0xfc, 0x64, 0x87, 0x5a, 0xc9, 0x43, 0x3c, 0x7b, 0x56, 0xb9, 0x27, 0xbc, 0x59, 0xf0, 0xf4,
- 0xd7, 0x19, 0x78, 0x79, 0xa9, 0xf1, 0xa5, 0x8e, 0xbe, 0x06, 0x60, 0xda, 0xee, 0x34, 0x10, 0x15,
- 0x91, 0xd8, 0x60, 0x4b, 0x1c, 0xe1, 0x9b, 0x17, 0xdb, 0x3c, 0xa7, 0x41, 0x2c, 0xcf, 0x72, 0x39,
- 0x08, 0x88, 0x13, 0xee, 0xce, 0x1c, 0xcd, 0x71, 0x47, 0x5f, 0x3f, 0x63, 0xa4, 0x0b, 0x89, 0xf9,
- 0x1e, 0x20, 0xdd, 0x32, 0xa9, 0x1d, 0x68, 0x7e, 0xe0, 0x51, 0x32, 0x31, 0xed, 0x11, 0x3f, 0x41,
- 0x8a, 0x7b, 0xf9, 0x21, 0xb1, 0x7c, 0xaa, 0xae, 0x09, 0x71, 0x3f, 0x92, 0x32, 0x0d, 0x9e, 0x40,
- 0x5e, 0x42, 0xa3, 0x90, 0xd2, 0x10, 0xe2, 0x58, 0xa3, 0xf6, 0xdb, 0x12, 0x94, 0x13, 0x75, 0x35,
- 0xbe, 0x02, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0x88, 0x44, 0x99, 0x61, 0xbd, 0xf0,
- 0xbe, 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0x1e, 0xb4,
- 0x22, 0xa7, 0x62, 0x26, 0xeb, 0x32, 0x51, 0x33, 0x92, 0xe0, 0xdb, 0xb0, 0xc1, 0x35, 0x26, 0x53,
- 0x2b, 0x30, 0x5d, 0x8b, 0x6a, 0xec, 0xf6, 0xe6, 0xf3, 0x93, 0x24, 0xf6, 0x6c, 0x9d, 0x31, 0x8e,
- 0x42, 0x02, 0xf3, 0xc8, 0xc7, 0x2d, 0x78, 0x8d, 0xab, 0x8d, 0xa8, 0x4d, 0x3d, 0x12, 0x50, 0x8d,
- 0x7e, 0x31, 0x25, 0x96, 0xaf, 0x11, 0xdb, 0xd0, 0xc6, 0xc4, 0x1f, 0xcb, 0x9b, 0xcc, 0xc0, 0x7e,
- 0x46, 0x96, 0xd4, 0x4b, 0x8c, 0x78, 0x10, 0xf2, 0x14, 0x4e, 0x6b, 0xd8, 0xc6, 0xc7, 0xc4, 0x1f,
- 0xe3, 0x3d, 0xb8, 0xc0, 0xad, 0xf8, 0x81, 0x67, 0xda, 0x23, 0x4d, 0x1f, 0x53, 0xfd, 0x91, 0x36,
- 0x0d, 0x86, 0x77, 0xe5, 0x57, 0x92, 0xfd, 0x73, 0x0f, 0xfb, 0x9c, 0xd3, 0x64, 0x94, 0xe3, 0x60,
- 0x78, 0x17, 0xf7, 0xa1, 0xc2, 0x26, 0x63, 0x62, 0x7e, 0x49, 0xb5, 0xa1, 0xe3, 0xf1, 0xa3, 0xb1,
- 0xba, 0x64, 0x6b, 0x4a, 0x44, 0xb0, 0xde, 0x0d, 0x15, 0x8e, 0x1c, 0x83, 0xee, 0xe5, 0xfb, 0x3d,
- 0x45, 0x69, 0xa9, 0xe5, 0xc8, 0xca, 0x7d, 0xc7, 0x63, 0x09, 0x35, 0x72, 0xe2, 0x00, 0x97, 0x45,
- 0x42, 0x8d, 0x9c, 0x28, 0xbc, 0xb7, 0x61, 0x43, 0xd7, 0xc5, 0x98, 0x4d, 0x5d, 0x0b, 0xef, 0x58,
- 0xbe, 0x8c, 0x52, 0xc1, 0xd2, 0xf5, 0x03, 0x41, 0x08, 0x73, 0xdc, 0xc7, 0x1f, 0xc2, 0xcb, 0xb3,
- 0x60, 0x25, 0x15, 0xd7, 0x17, 0x46, 0x39, 0xaf, 0x7a, 0x1b, 0x36, 0xdc, 0xd3, 0x45, 0x45, 0x9c,
- 0xea, 0xd1, 0x3d, 0x9d, 0x57, 0xfb, 0x00, 0x36, 0xdd, 0xb1, 0xbb, 0xa8, 0x77, 0x3d, 0xa9, 0x87,
- 0xdd, 0xb1, 0x3b, 0xaf, 0xf8, 0x16, 0xbf, 0x70, 0x7b, 0x54, 0x27, 0x01, 0x35, 0xe4, 0x8b, 0x49,
- 0x7a, 0x42, 0x80, 0x77, 0x01, 0xe9, 0xba, 0x46, 0x6d, 0x72, 0x62, 0x51, 0x8d, 0x78, 0xd4, 0x26,
- 0xbe, 0x7c, 0x39, 0x49, 0xae, 0xea, 0xba, 0xc2, 0xa5, 0x0d, 0x2e, 0xc4, 0xd7, 0x61, 0xdd, 0x39,
- 0x79, 0xa8, 0x8b, 0x94, 0xd4, 0x5c, 0x8f, 0x0e, 0xcd, 0xa7, 0xf2, 0x9b, 0x3c, 0xbe, 0x6b, 0x4c,
- 0xc0, 0x13, 0xb2, 0xc7, 0x61, 0x7c, 0x0d, 0x90, 0xee, 0x8f, 0x89, 0xe7, 0xf2, 0x3d, 0xd9, 0x77,
- 0x89, 0x4e, 0xe5, 0xb7, 0x04, 0x55, 0xe0, 0x9d, 0x08, 0x66, 0x4b, 0xc2, 0x7f, 0x62, 0x0e, 0x83,
- 0xc8, 0xe2, 0x55, 0xb1, 0x24, 0x38, 0x16, 0x5a, 0xdb, 0x01, 0xc4, 0x42, 0x91, 0xea, 0x78, 0x87,
- 0xd3, 0xaa, 0xee, 0xd8, 0x4d, 0xf6, 0xfb, 0x06, 0xac, 0x32, 0xe6, 0xac, 0xd3, 0x6b, 0xa2, 0x20,
- 0x73, 0xc7, 0x89, 0x1e, 0x6f, 0xc1, 0x05, 0x46, 0x9a, 0xd0, 0x80, 0x18, 0x24, 0x20, 0x09, 0xf6,
- 0xbb, 0x9c, 0xcd, 0xe2, 0x7e, 0x14, 0x0a, 0x53, 0x7e, 0x7a, 0xd3, 0x93, 0xd3, 0x38, 0xb3, 0x6e,
- 0x08, 0x3f, 0x19, 0x16, 0xe5, 0xd6, 0xf7, 0x56, 0x74, 0xd7, 0xf6, 0xa0, 0x92, 0x4c, 0x7c, 0x5c,
- 0x02, 0x91, 0xfa, 0x48, 0x62, 0x55, 0x50, 0xb3, 0xdb, 0x62, 0xf5, 0xcb, 0xe7, 0x0a, 0xca, 0xb0,
- 0x3a, 0xea, 0xb0, 0x3d, 0x50, 0x34, 0xf5, 0xb8, 0x33, 0x68, 0x1f, 0x29, 0x28, 0x9b, 0x28, 0xd8,
- 0x1f, 0xe4, 0x8a, 0x6f, 0xa3, 0xab, 0xb5, 0xaf, 0x33, 0x50, 0x4d, 0xdf, 0xc0, 0xf0, 0x8f, 0xe0,
- 0x62, 0xf4, 0x5c, 0xe2, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0x45, 0x4e, 0x88, 0x38, 0x1d, 0xe3,
- 0x9c, 0xd8, 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0xbd, 0x4d, 0x48, 0x80, 0x0f, 0xe1,
- 0xb2, 0xed, 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0xa8, 0xd2, 0x88, 0xae, 0x53,
- 0xdf, 0x77, 0xc4, 0x49, 0x18, 0x5b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x76, 0x44, 0x34, 0x42,
- 0xea, 0x5c, 0xfe, 0x66, 0xcf, 0xca, 0xdf, 0x57, 0xa0, 0x34, 0x21, 0xae, 0x46, 0xed, 0xc0, 0x3b,
- 0xe5, 0x75, 0x77, 0x51, 0x2d, 0x4e, 0x88, 0xab, 0xb0, 0xf6, 0x0b, 0xb9, 0xfe, 0x3c, 0xc8, 0x15,
- 0x8b, 0xa8, 0xf4, 0x20, 0x57, 0x2c, 0x21, 0xa8, 0xfd, 0x33, 0x0b, 0x95, 0x64, 0x1d, 0xce, 0xae,
- 0x35, 0x3a, 0x3f, 0xb2, 0x24, 0xbe, 0xa9, 0xbd, 0xf1, 0x8d, 0x55, 0x7b, 0xbd, 0xc9, 0xce, 0xb2,
- 0xbd, 0x82, 0xa8, 0x8e, 0x55, 0xa1, 0xc9, 0xea, 0x08, 0x96, 0x6c, 0x54, 0x54, 0x23, 0x45, 0x35,
- 0x6c, 0xe1, 0x03, 0x28, 0x3c, 0xf4, 0xb9, 0xed, 0x02, 0xb7, 0xfd, 0xe6, 0x37, 0xdb, 0x7e, 0xd0,
- 0xe7, 0xc6, 0x4b, 0x0f, 0xfa, 0x5a, 0xa7, 0xab, 0x1e, 0x35, 0x0e, 0xd5, 0x50, 0x1d, 0x5f, 0x82,
- 0x9c, 0x45, 0xbe, 0x3c, 0x4d, 0x9f, 0x7a, 0x1c, 0x3a, 0xef, 0x24, 0x5c, 0x82, 0xdc, 0x13, 0x4a,
- 0x1e, 0xa5, 0xcf, 0x1a, 0x0e, 0x7d, 0x8f, 0x8b, 0x61, 0x17, 0xf2, 0x3c, 0x5e, 0x18, 0x20, 0x8c,
- 0x18, 0x7a, 0x09, 0x17, 0x21, 0xd7, 0xec, 0xaa, 0x6c, 0x41, 0x20, 0xa8, 0x08, 0x54, 0xeb, 0xb5,
- 0x95, 0xa6, 0x82, 0x32, 0xb5, 0xdb, 0x50, 0x10, 0x41, 0x60, 0x8b, 0x25, 0x0e, 0x03, 0x7a, 0x29,
- 0x6c, 0x86, 0x36, 0xa4, 0x48, 0x7a, 0x7c, 0xb4, 0xaf, 0xa8, 0x28, 0x93, 0x9e, 0xea, 0x1c, 0xca,
- 0xd7, 0x7c, 0xa8, 0x24, 0x0b, 0xf1, 0x17, 0x73, 0xc9, 0xfe, 0x9b, 0x04, 0xe5, 0x44, 0x61, 0xcd,
- 0x2a, 0x22, 0x62, 0x59, 0xce, 0x13, 0x8d, 0x58, 0x26, 0xf1, 0xc3, 0xd4, 0x00, 0x0e, 0x35, 0x18,
- 0x72, 0xde, 0xa9, 0x7b, 0x41, 0x4b, 0x24, 0x8f, 0x0a, 0xb5, 0x3f, 0x4a, 0x80, 0xe6, 0x2b, 0xdb,
- 0x39, 0x37, 0xa5, 0x1f, 0xd2, 0xcd, 0xda, 0x1f, 0x24, 0xa8, 0xa6, 0xcb, 0xd9, 0x39, 0xf7, 0xae,
- 0xfc, 0xa0, 0xee, 0xfd, 0x23, 0x03, 0xab, 0xa9, 0x22, 0xf6, 0xbc, 0xde, 0x7d, 0x01, 0xeb, 0xa6,
- 0x41, 0x27, 0xae, 0x13, 0x50, 0x5b, 0x3f, 0xd5, 0x2c, 0xfa, 0x98, 0x5a, 0x72, 0x8d, 0x6f, 0x1a,
- 0xbb, 0xdf, 0x5c, 0x26, 0xd7, 0xdb, 0x33, 0xbd, 0x43, 0xa6, 0xb6, 0xb7, 0xd1, 0x6e, 0x29, 0x47,
- 0xbd, 0xee, 0x40, 0xe9, 0x34, 0x3f, 0xd3, 0x8e, 0x3b, 0x3f, 0xed, 0x74, 0x3f, 0xe9, 0xa8, 0xc8,
- 0x9c, 0xa3, 0x7d, 0x8f, 0xcb, 0xbe, 0x07, 0x68, 0xde, 0x29, 0x7c, 0x11, 0x96, 0xb9, 0x85, 0x5e,
- 0xc2, 0x1b, 0xb0, 0xd6, 0xe9, 0x6a, 0xfd, 0x76, 0x4b, 0xd1, 0x94, 0xfb, 0xf7, 0x95, 0xe6, 0xa0,
- 0x2f, 0x1e, 0x3e, 0x62, 0xf6, 0x20, 0xb5, 0xc0, 0x6b, 0xbf, 0xcf, 0xc2, 0xc6, 0x12, 0x4f, 0x70,
- 0x23, 0xbc, 0xb2, 0x88, 0x5b, 0xd4, 0x8d, 0xf3, 0x78, 0x5f, 0x67, 0x35, 0x43, 0x8f, 0x78, 0x41,
- 0x78, 0xc3, 0xb9, 0x06, 0x2c, 0x4a, 0x76, 0x60, 0x0e, 0x4d, 0xea, 0x85, 0xef, 0x44, 0xe2, 0x1e,
- 0xb3, 0x36, 0xc3, 0xc5, 0x53, 0xd1, 0xbb, 0x80, 0x5d, 0xc7, 0x37, 0x03, 0xf3, 0x31, 0xd5, 0x4c,
- 0x3b, 0x7a, 0x54, 0x62, 0xf7, 0x9a, 0x9c, 0x8a, 0x22, 0x49, 0xdb, 0x0e, 0x62, 0xb6, 0x4d, 0x47,
- 0x64, 0x8e, 0xcd, 0x36, 0xf3, 0xac, 0x8a, 0x22, 0x49, 0xcc, 0xbe, 0x02, 0x15, 0xc3, 0x99, 0xb2,
- 0x62, 0x4f, 0xf0, 0xd8, 0xd9, 0x21, 0xa9, 0x65, 0x81, 0xc5, 0x94, 0xb0, 0x8c, 0x9f, 0xbd, 0x66,
- 0x55, 0xd4, 0xb2, 0xc0, 0x04, 0xe5, 0x2a, 0xac, 0x91, 0xd1, 0xc8, 0x63, 0xc6, 0x23, 0x43, 0xe2,
- 0x62, 0x52, 0x8d, 0x61, 0x4e, 0xdc, 0x7a, 0x00, 0xc5, 0x28, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0xd0,
- 0x5c, 0x71, 0xdb, 0xce, 0xec, 0x94, 0xd4, 0xa2, 0x1d, 0x09, 0xaf, 0x40, 0xc5, 0xf4, 0xb5, 0xd9,
- 0xe3, 0x7c, 0x66, 0x3b, 0xb3, 0x53, 0x54, 0xcb, 0xa6, 0x1f, 0x3f, 0x6c, 0xd6, 0xbe, 0xca, 0x40,
- 0x35, 0xfd, 0x71, 0x01, 0xb7, 0xa0, 0x68, 0x39, 0x3a, 0xe1, 0xa9, 0x25, 0xbe, 0x6c, 0xed, 0x3c,
- 0xe7, 0x7b, 0x44, 0xfd, 0x30, 0xe4, 0xab, 0xb1, 0xe6, 0xd6, 0xdf, 0x25, 0x28, 0x46, 0x30, 0xbe,
- 0x00, 0x39, 0x97, 0x04, 0x63, 0x6e, 0x2e, 0xbf, 0x9f, 0x41, 0x92, 0xca, 0xdb, 0x0c, 0xf7, 0x5d,
- 0x62, 0xf3, 0x14, 0x08, 0x71, 0xd6, 0x66, 0xf3, 0x6a, 0x51, 0x62, 0xf0, 0x5b, 0x8f, 0x33, 0x99,
- 0x50, 0x3b, 0xf0, 0xa3, 0x79, 0x0d, 0xf1, 0x66, 0x08, 0xe3, 0x77, 0x60, 0x3d, 0xf0, 0x88, 0x69,
- 0xa5, 0xb8, 0x39, 0xce, 0x45, 0x91, 0x20, 0x26, 0xef, 0xc1, 0xa5, 0xc8, 0xae, 0x41, 0x03, 0xa2,
- 0x8f, 0xa9, 0x31, 0x53, 0x2a, 0xf0, 0xd7, 0x8d, 0x8b, 0x21, 0xa1, 0x15, 0xca, 0x23, 0xdd, 0xda,
- 0xd7, 0x12, 0xac, 0x47, 0xf7, 0x34, 0x23, 0x0e, 0xd6, 0x11, 0x00, 0xb1, 0x6d, 0x27, 0x48, 0x86,
- 0x6b, 0x31, 0x95, 0x17, 0xf4, 0xea, 0x8d, 0x58, 0x49, 0x4d, 0x18, 0xd8, 0x9a, 0x00, 0xcc, 0x24,
- 0x67, 0x86, 0xed, 0x32, 0x94, 0xc3, 0x2f, 0x47, 0xfc, 0xf3, 0xa3, 0xb8, 0xd9, 0x83, 0x80, 0xd8,
- 0x85, 0x0e, 0x6f, 0x42, 0xfe, 0x84, 0x8e, 0x4c, 0x3b, 0x7c, 0x0f, 0x16, 0x8d, 0xe8, 0xfd, 0x25,
- 0x17, 0xbf, 0xbf, 0xec, 0xff, 0x46, 0x82, 0x0d, 0xdd, 0x99, 0xcc, 0xfb, 0xbb, 0x8f, 0xe6, 0x9e,
- 0x17, 0xfc, 0x8f, 0xa5, 0xcf, 0x3f, 0x1a, 0x99, 0xc1, 0x78, 0x7a, 0x52, 0xd7, 0x9d, 0xc9, 0xee,
- 0xc8, 0xb1, 0x88, 0x3d, 0x9a, 0x7d, 0x3f, 0xe5, 0x7f, 0xf4, 0x1b, 0x23, 0x6a, 0xdf, 0x18, 0x39,
- 0x89, 0xaf, 0xa9, 0xf7, 0x66, 0x7f, 0xff, 0x27, 0x49, 0x7f, 0xca, 0x64, 0x0f, 0x7a, 0xfb, 0x7f,
- 0xce, 0x6c, 0x1d, 0x88, 0xee, 0x7a, 0x51, 0x78, 0x54, 0x3a, 0xb4, 0xa8, 0xce, 0x86, 0xfc, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0xff, 0x3e, 0xe8, 0xef, 0xc4, 0x9b, 0x1d, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
deleted file mode 100644
index ed08fcb..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
+++ /dev/null
@@ -1,883 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// The messages in this file describe the definitions found in .proto files.
-// A valid .proto file can be translated directly to a FileDescriptorProto
-// without any other information (e.g. without reading its imports).
-
-
-syntax = "proto2";
-
-package google.protobuf;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DescriptorProtos";
-option csharp_namespace = "Google.Protobuf.Reflection";
-option objc_class_prefix = "GPB";
-option cc_enable_arenas = true;
-
-// descriptor.proto must be optimized for speed because reflection-based
-// algorithms don't work during bootstrapping.
-option optimize_for = SPEED;
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-message FileDescriptorSet {
- repeated FileDescriptorProto file = 1;
-}
-
-// Describes a complete .proto file.
-message FileDescriptorProto {
- optional string name = 1; // file name, relative to root of source tree
- optional string package = 2; // e.g. "foo", "foo.bar", etc.
-
- // Names of files imported by this file.
- repeated string dependency = 3;
- // Indexes of the public imported files in the dependency list above.
- repeated int32 public_dependency = 10;
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- repeated int32 weak_dependency = 11;
-
- // All top-level definitions in this file.
- repeated DescriptorProto message_type = 4;
- repeated EnumDescriptorProto enum_type = 5;
- repeated ServiceDescriptorProto service = 6;
- repeated FieldDescriptorProto extension = 7;
-
- optional FileOptions options = 8;
-
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- optional SourceCodeInfo source_code_info = 9;
-
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- optional string syntax = 12;
-}
-
-// Describes a message type.
-message DescriptorProto {
- optional string name = 1;
-
- repeated FieldDescriptorProto field = 2;
- repeated FieldDescriptorProto extension = 6;
-
- repeated DescriptorProto nested_type = 3;
- repeated EnumDescriptorProto enum_type = 4;
-
- message ExtensionRange {
- optional int32 start = 1;
- optional int32 end = 2;
-
- optional ExtensionRangeOptions options = 3;
- }
- repeated ExtensionRange extension_range = 5;
-
- repeated OneofDescriptorProto oneof_decl = 8;
-
- optional MessageOptions options = 7;
-
- // Range of reserved tag numbers. Reserved tag numbers may not be used by
- // fields or extension ranges in the same message. Reserved ranges may
- // not overlap.
- message ReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Exclusive.
- }
- repeated ReservedRange reserved_range = 9;
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- repeated string reserved_name = 10;
-}
-
-message ExtensionRangeOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-// Describes a field within a message.
-message FieldDescriptorProto {
- enum Type {
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- TYPE_DOUBLE = 1;
- TYPE_FLOAT = 2;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- TYPE_INT64 = 3;
- TYPE_UINT64 = 4;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- TYPE_INT32 = 5;
- TYPE_FIXED64 = 6;
- TYPE_FIXED32 = 7;
- TYPE_BOOL = 8;
- TYPE_STRING = 9;
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- TYPE_GROUP = 10;
- TYPE_MESSAGE = 11; // Length-delimited aggregate.
-
- // New in version 2.
- TYPE_BYTES = 12;
- TYPE_UINT32 = 13;
- TYPE_ENUM = 14;
- TYPE_SFIXED32 = 15;
- TYPE_SFIXED64 = 16;
- TYPE_SINT32 = 17; // Uses ZigZag encoding.
- TYPE_SINT64 = 18; // Uses ZigZag encoding.
- };
-
- enum Label {
- // 0 is reserved for errors
- LABEL_OPTIONAL = 1;
- LABEL_REQUIRED = 2;
- LABEL_REPEATED = 3;
- };
-
- optional string name = 1;
- optional int32 number = 3;
- optional Label label = 4;
-
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- optional Type type = 5;
-
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- optional string type_name = 6;
-
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- optional string extendee = 2;
-
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- optional string default_value = 7;
-
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- optional int32 oneof_index = 9;
-
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- optional string json_name = 10;
-
- optional FieldOptions options = 8;
-}
-
-// Describes a oneof.
-message OneofDescriptorProto {
- optional string name = 1;
- optional OneofOptions options = 2;
-}
-
-// Describes an enum type.
-message EnumDescriptorProto {
- optional string name = 1;
-
- repeated EnumValueDescriptorProto value = 2;
-
- optional EnumOptions options = 3;
-
- // Range of reserved numeric values. Reserved values may not be used by
- // entries in the same enum. Reserved ranges may not overlap.
- //
- // Note that this is distinct from DescriptorProto.ReservedRange in that it
- // is inclusive such that it can appropriately represent the entire int32
- // domain.
- message EnumReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Inclusive.
- }
-
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- repeated EnumReservedRange reserved_range = 4;
-
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- repeated string reserved_name = 5;
-}
-
-// Describes a value within an enum.
-message EnumValueDescriptorProto {
- optional string name = 1;
- optional int32 number = 2;
-
- optional EnumValueOptions options = 3;
-}
-
-// Describes a service.
-message ServiceDescriptorProto {
- optional string name = 1;
- repeated MethodDescriptorProto method = 2;
-
- optional ServiceOptions options = 3;
-}
-
-// Describes a method of a service.
-message MethodDescriptorProto {
- optional string name = 1;
-
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- optional string input_type = 2;
- optional string output_type = 3;
-
- optional MethodOptions options = 4;
-
- // Identifies if client streams multiple client messages
- optional bool client_streaming = 5 [default=false];
- // Identifies if server streams multiple server messages
- optional bool server_streaming = 6 [default=false];
-}
-
-
-// ===================================================================
-// Options
-
-// Each of the definitions above may have "options" attached. These are
-// just annotations which may cause code to be generated slightly differently
-// or may contain hints for code that manipulates protocol messages.
-//
-// Clients may define custom options as extensions of the *Options messages.
-// These extensions may not yet be known at parsing time, so the parser cannot
-// store the values in them. Instead it stores them in a field in the *Options
-// message called uninterpreted_option. This field must have the same name
-// across all *Options messages. We then use this field to populate the
-// extensions when we build a descriptor, at which point all protos have been
-// parsed and so all extensions are known.
-//
-// Extension numbers for custom options may be chosen as follows:
-// * For options which will only be used within a single application or
-// organization, or for experimental options, use field numbers 50000
-// through 99999. It is up to you to ensure that you do not use the
-// same number for multiple options.
-// * For options which will be published and used publicly by multiple
-// independent entities, e-mail protobuf-global-extension-registry@google.com
-// to reserve extension numbers. Simply provide your project name (e.g.
-// Objective-C plugin) and your project website (if available) -- there's no
-// need to explain how you intend to use them. Usually you only need one
-// extension number. You can declare multiple options with only one extension
-// number by putting them in a sub-message. See the Custom Options section of
-// the docs for examples:
-// https://developers.google.com/protocol-buffers/docs/proto#options
-// If this turns out to be popular, a web service will be set up
-// to automatically assign option numbers.
-
-
-message FileOptions {
-
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- optional string java_package = 1;
-
-
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- optional string java_outer_classname = 8;
-
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- optional bool java_multiple_files = 10 [default=false];
-
- // This option does nothing.
- optional bool java_generate_equals_and_hash = 20 [deprecated=true];
-
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- optional bool java_string_check_utf8 = 27 [default=false];
-
-
- // Generated classes can be optimized for speed or code size.
- enum OptimizeMode {
- SPEED = 1; // Generate complete code for parsing, serialization,
- // etc.
- CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
- LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
- }
- optional OptimizeMode optimize_for = 9 [default=SPEED];
-
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- optional string go_package = 11;
-
-
-
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- optional bool cc_generic_services = 16 [default=false];
- optional bool java_generic_services = 17 [default=false];
- optional bool py_generic_services = 18 [default=false];
- optional bool php_generic_services = 42 [default=false];
-
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- optional bool deprecated = 23 [default=false];
-
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- optional bool cc_enable_arenas = 31 [default=false];
-
-
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- optional string objc_class_prefix = 36;
-
- // Namespace for generated classes; defaults to the package.
- optional string csharp_namespace = 37;
-
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- optional string swift_prefix = 39;
-
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- optional string php_class_prefix = 40;
-
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- optional string php_namespace = 41;
-
-
- // Use this option to change the namespace of php generated metadata classes.
- // Default is empty. When this option is empty, the proto file name will be used
- // for determining the namespace.
- optional string php_metadata_namespace = 44;
-
- // Use this option to change the package of ruby generated classes. Default
- // is empty. When this option is not set, the package name will be used for
- // determining the ruby package.
- optional string ruby_package = 45;
-
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message.
- // See the documentation for the "Options" section above.
- extensions 1000 to max;
-
- reserved 38;
-}
-
-message MessageOptions {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- optional bool message_set_wire_format = 1 [default=false];
-
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- optional bool no_standard_descriptor_accessor = 2 [default=false];
-
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- optional bool deprecated = 3 [default=false];
-
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- optional bool map_entry = 7;
-
- reserved 8; // javalite_serializable
- reserved 9; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message FieldOptions {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- optional CType ctype = 1 [default = STRING];
- enum CType {
- // Default mode.
- STRING = 0;
-
- CORD = 1;
-
- STRING_PIECE = 2;
- }
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- optional bool packed = 2;
-
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- optional JSType jstype = 6 [default = JS_NORMAL];
- enum JSType {
- // Use the default type.
- JS_NORMAL = 0;
-
- // Use JavaScript strings.
- JS_STRING = 1;
-
- // Use JavaScript numbers.
- JS_NUMBER = 2;
- }
-
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- optional bool lazy = 5 [default=false];
-
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- optional bool deprecated = 3 [default=false];
-
- // For Google-internal migration only. Do not use.
- optional bool weak = 10 [default=false];
-
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-
- reserved 4; // removed jtype
-}
-
-message OneofOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumOptions {
-
- // Set this option to true to allow mapping different tag names to the same
- // value.
- optional bool allow_alias = 2;
-
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- optional bool deprecated = 3 [default=false];
-
- reserved 5; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumValueOptions {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- optional bool deprecated = 1 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message ServiceOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- optional bool deprecated = 33 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message MethodOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- optional bool deprecated = 33 [default=false];
-
- // Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
- // or neither? HTTP based RPC implementation may choose GET verb for safe
- // methods, and PUT verb for idempotent methods instead of the default POST.
- enum IdempotencyLevel {
- IDEMPOTENCY_UNKNOWN = 0;
- NO_SIDE_EFFECTS = 1; // implies idempotent
- IDEMPOTENT = 2; // idempotent, but may have side effects
- }
- optional IdempotencyLevel idempotency_level =
- 34 [default=IDEMPOTENCY_UNKNOWN];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-message UninterpretedOption {
- // The name of the uninterpreted option. Each string represents a segment in
- // a dot-separated name. is_extension is true iff a segment represents an
- // extension (denoted with parentheses in options specs in .proto files).
- // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
- // "foo.(bar.baz).qux".
- message NamePart {
- required string name_part = 1;
- required bool is_extension = 2;
- }
- repeated NamePart name = 2;
-
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- optional string identifier_value = 3;
- optional uint64 positive_int_value = 4;
- optional int64 negative_int_value = 5;
- optional double double_value = 6;
- optional bytes string_value = 7;
- optional string aggregate_value = 8;
-}
-
-// ===================================================================
-// Optional source code info
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-message SourceCodeInfo {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- repeated Location location = 1;
- message Location {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- repeated int32 path = 1 [packed=true];
-
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- repeated int32 span = 2 [packed=true];
-
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- optional string leading_comments = 3;
- optional string trailing_comments = 4;
- repeated string leading_detached_comments = 6;
- }
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-message GeneratedCodeInfo {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- repeated Annotation annotation = 1;
- message Annotation {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- repeated int32 path = 1 [packed=true];
-
- // Identifies the filesystem path to the original source .proto.
- optional string source_file = 2;
-
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- optional int32 begin = 3;
-
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- optional int32 end = 4;
- }
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go
deleted file mode 100644
index 70276e8..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/any.go
+++ /dev/null
@@ -1,141 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package ptypes
-
-// This file implements functions to marshal proto.Message to/from
-// google.protobuf.Any message.
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/ptypes/any"
-)
-
-const googleApis = "type.googleapis.com/"
-
-// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
-//
-// Note that regular type assertions should be done using the Is
-// function. AnyMessageName is provided for less common use cases like filtering a
-// sequence of Any messages based on a set of allowed message type names.
-func AnyMessageName(any *any.Any) (string, error) {
- if any == nil {
- return "", fmt.Errorf("message is nil")
- }
- slash := strings.LastIndex(any.TypeUrl, "/")
- if slash < 0 {
- return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
- }
- return any.TypeUrl[slash+1:], nil
-}
-
-// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
-func MarshalAny(pb proto.Message) (*any.Any, error) {
- value, err := proto.Marshal(pb)
- if err != nil {
- return nil, err
- }
- return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
-}
-
-// DynamicAny is a value that can be passed to UnmarshalAny to automatically
-// allocate a proto.Message for the type specified in a google.protobuf.Any
-// message. The allocated message is stored in the embedded proto.Message.
-//
-// Example:
-//
-// var x ptypes.DynamicAny
-// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
-// fmt.Printf("unmarshaled message: %v", x.Message)
-type DynamicAny struct {
- proto.Message
-}
-
-// Empty returns a new proto.Message of the type specified in a
-// google.protobuf.Any message. It returns an error if corresponding message
-// type isn't linked in.
-func Empty(any *any.Any) (proto.Message, error) {
- aname, err := AnyMessageName(any)
- if err != nil {
- return nil, err
- }
-
- t := proto.MessageType(aname)
- if t == nil {
- return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
- }
- return reflect.New(t.Elem()).Interface().(proto.Message), nil
-}
-
-// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
-// message and places the decoded result in pb. It returns an error if type of
-// contents of Any message does not match type of pb message.
-//
-// pb can be a proto.Message, or a *DynamicAny.
-func UnmarshalAny(any *any.Any, pb proto.Message) error {
- if d, ok := pb.(*DynamicAny); ok {
- if d.Message == nil {
- var err error
- d.Message, err = Empty(any)
- if err != nil {
- return err
- }
- }
- return UnmarshalAny(any, d.Message)
- }
-
- aname, err := AnyMessageName(any)
- if err != nil {
- return err
- }
-
- mname := proto.MessageName(pb)
- if aname != mname {
- return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
- }
- return proto.Unmarshal(any.Value, pb)
-}
-
-// Is returns true if any value contains a given message type.
-func Is(any *any.Any, pb proto.Message) bool {
- // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb),
- // but it avoids scanning TypeUrl for the slash.
- if any == nil {
- return false
- }
- name := proto.MessageName(pb)
- prefix := len(any.TypeUrl) - len(name)
- return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
deleted file mode 100644
index 78ee523..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
+++ /dev/null
@@ -1,200 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/any.proto
-
-package any
-
-import (
- fmt "fmt"
- proto "github.com/golang/protobuf/proto"
- math "math"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
-
-// `Any` contains an arbitrary serialized protocol buffer message along with a
-// URL that describes the type of the serialized message.
-//
-// Protobuf library provides support to pack/unpack Any values in the form
-// of utility functions or additional generated methods of the Any type.
-//
-// Example 1: Pack and unpack a message in C++.
-//
-// Foo foo = ...;
-// Any any;
-// any.PackFrom(foo);
-// ...
-// if (any.UnpackTo(&foo)) {
-// ...
-// }
-//
-// Example 2: Pack and unpack a message in Java.
-//
-// Foo foo = ...;
-// Any any = Any.pack(foo);
-// ...
-// if (any.is(Foo.class)) {
-// foo = any.unpack(Foo.class);
-// }
-//
-// Example 3: Pack and unpack a message in Python.
-//
-// foo = Foo(...)
-// any = Any()
-// any.Pack(foo)
-// ...
-// if any.Is(Foo.DESCRIPTOR):
-// any.Unpack(foo)
-// ...
-//
-// Example 4: Pack and unpack a message in Go
-//
-// foo := &pb.Foo{...}
-// any, err := ptypes.MarshalAny(foo)
-// ...
-// foo := &pb.Foo{}
-// if err := ptypes.UnmarshalAny(any, foo); err != nil {
-// ...
-// }
-//
-// The pack methods provided by protobuf library will by default use
-// 'type.googleapis.com/full.type.name' as the type URL and the unpack
-// methods only use the fully qualified type name after the last '/'
-// in the type URL, for example "foo.bar.com/x/y.z" will yield type
-// name "y.z".
-//
-//
-// JSON
-// ====
-// The JSON representation of an `Any` value uses the regular
-// representation of the deserialized, embedded message, with an
-// additional field `@type` which contains the type URL. Example:
-//
-// package google.profile;
-// message Person {
-// string first_name = 1;
-// string last_name = 2;
-// }
-//
-// {
-// "@type": "type.googleapis.com/google.profile.Person",
-// "firstName": ,
-// "lastName":
-// }
-//
-// If the embedded message type is well-known and has a custom JSON
-// representation, that representation will be embedded adding a field
-// `value` which holds the custom JSON in addition to the `@type`
-// field. Example (for message [google.protobuf.Duration][]):
-//
-// {
-// "@type": "type.googleapis.com/google.protobuf.Duration",
-// "value": "1.212s"
-// }
-//
-type Any struct {
- // A URL/resource name that uniquely identifies the type of the serialized
- // protocol buffer message. The last segment of the URL's path must represent
- // the fully qualified name of the type (as in
- // `path/google.protobuf.Duration`). The name should be in a canonical form
- // (e.g., leading "." is not accepted).
- //
- // In practice, teams usually precompile into the binary all types that they
- // expect it to use in the context of Any. However, for URLs which use the
- // scheme `http`, `https`, or no scheme, one can optionally set up a type
- // server that maps type URLs to message definitions as follows:
- //
- // * If no scheme is provided, `https` is assumed.
- // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
- // value in binary format, or produce an error.
- // * Applications are allowed to cache lookup results based on the
- // URL, or have them precompiled into a binary to avoid any
- // lookup. Therefore, binary compatibility needs to be preserved
- // on changes to types. (Use versioned type names to manage
- // breaking changes.)
- //
- // Note: this functionality is not currently available in the official
- // protobuf release, and it is not used for type URLs beginning with
- // type.googleapis.com.
- //
- // Schemes other than `http`, `https` (or the empty scheme) might be
- // used with implementation specific semantics.
- //
- TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"`
- // Must be a valid serialized protocol buffer of the above specified type.
- Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Any) Reset() { *m = Any{} }
-func (m *Any) String() string { return proto.CompactTextString(m) }
-func (*Any) ProtoMessage() {}
-func (*Any) Descriptor() ([]byte, []int) {
- return fileDescriptor_b53526c13ae22eb4, []int{0}
-}
-
-func (*Any) XXX_WellKnownType() string { return "Any" }
-
-func (m *Any) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Any.Unmarshal(m, b)
-}
-func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Any.Marshal(b, m, deterministic)
-}
-func (m *Any) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Any.Merge(m, src)
-}
-func (m *Any) XXX_Size() int {
- return xxx_messageInfo_Any.Size(m)
-}
-func (m *Any) XXX_DiscardUnknown() {
- xxx_messageInfo_Any.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Any proto.InternalMessageInfo
-
-func (m *Any) GetTypeUrl() string {
- if m != nil {
- return m.TypeUrl
- }
- return ""
-}
-
-func (m *Any) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func init() {
- proto.RegisterType((*Any)(nil), "google.protobuf.Any")
-}
-
-func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_b53526c13ae22eb4) }
-
-var fileDescriptor_b53526c13ae22eb4 = []byte{
- // 185 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4,
- 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a,
- 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46,
- 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7,
- 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce,
- 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52,
- 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc,
- 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c,
- 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce,
- 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff,
- 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
deleted file mode 100644
index 4932942..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/any/any.proto
+++ /dev/null
@@ -1,154 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option go_package = "github.com/golang/protobuf/ptypes/any";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "AnyProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// `Any` contains an arbitrary serialized protocol buffer message along with a
-// URL that describes the type of the serialized message.
-//
-// Protobuf library provides support to pack/unpack Any values in the form
-// of utility functions or additional generated methods of the Any type.
-//
-// Example 1: Pack and unpack a message in C++.
-//
-// Foo foo = ...;
-// Any any;
-// any.PackFrom(foo);
-// ...
-// if (any.UnpackTo(&foo)) {
-// ...
-// }
-//
-// Example 2: Pack and unpack a message in Java.
-//
-// Foo foo = ...;
-// Any any = Any.pack(foo);
-// ...
-// if (any.is(Foo.class)) {
-// foo = any.unpack(Foo.class);
-// }
-//
-// Example 3: Pack and unpack a message in Python.
-//
-// foo = Foo(...)
-// any = Any()
-// any.Pack(foo)
-// ...
-// if any.Is(Foo.DESCRIPTOR):
-// any.Unpack(foo)
-// ...
-//
-// Example 4: Pack and unpack a message in Go
-//
-// foo := &pb.Foo{...}
-// any, err := ptypes.MarshalAny(foo)
-// ...
-// foo := &pb.Foo{}
-// if err := ptypes.UnmarshalAny(any, foo); err != nil {
-// ...
-// }
-//
-// The pack methods provided by protobuf library will by default use
-// 'type.googleapis.com/full.type.name' as the type URL and the unpack
-// methods only use the fully qualified type name after the last '/'
-// in the type URL, for example "foo.bar.com/x/y.z" will yield type
-// name "y.z".
-//
-//
-// JSON
-// ====
-// The JSON representation of an `Any` value uses the regular
-// representation of the deserialized, embedded message, with an
-// additional field `@type` which contains the type URL. Example:
-//
-// package google.profile;
-// message Person {
-// string first_name = 1;
-// string last_name = 2;
-// }
-//
-// {
-// "@type": "type.googleapis.com/google.profile.Person",
-// "firstName": ,
-// "lastName":
-// }
-//
-// If the embedded message type is well-known and has a custom JSON
-// representation, that representation will be embedded adding a field
-// `value` which holds the custom JSON in addition to the `@type`
-// field. Example (for message [google.protobuf.Duration][]):
-//
-// {
-// "@type": "type.googleapis.com/google.protobuf.Duration",
-// "value": "1.212s"
-// }
-//
-message Any {
- // A URL/resource name that uniquely identifies the type of the serialized
- // protocol buffer message. The last segment of the URL's path must represent
- // the fully qualified name of the type (as in
- // `path/google.protobuf.Duration`). The name should be in a canonical form
- // (e.g., leading "." is not accepted).
- //
- // In practice, teams usually precompile into the binary all types that they
- // expect it to use in the context of Any. However, for URLs which use the
- // scheme `http`, `https`, or no scheme, one can optionally set up a type
- // server that maps type URLs to message definitions as follows:
- //
- // * If no scheme is provided, `https` is assumed.
- // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
- // value in binary format, or produce an error.
- // * Applications are allowed to cache lookup results based on the
- // URL, or have them precompiled into a binary to avoid any
- // lookup. Therefore, binary compatibility needs to be preserved
- // on changes to types. (Use versioned type names to manage
- // breaking changes.)
- //
- // Note: this functionality is not currently available in the official
- // protobuf release, and it is not used for type URLs beginning with
- // type.googleapis.com.
- //
- // Schemes other than `http`, `https` (or the empty scheme) might be
- // used with implementation specific semantics.
- //
- string type_url = 1;
-
- // Must be a valid serialized protocol buffer of the above specified type.
- bytes value = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go
deleted file mode 100644
index c0d595d..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/doc.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-/*
-Package ptypes contains code for interacting with well-known types.
-*/
-package ptypes
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go
deleted file mode 100644
index 26d1ca2..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/duration.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package ptypes
-
-// This file implements conversions between google.protobuf.Duration
-// and time.Duration.
-
-import (
- "errors"
- "fmt"
- "time"
-
- durpb "github.com/golang/protobuf/ptypes/duration"
-)
-
-const (
- // Range of a durpb.Duration in seconds, as specified in
- // google/protobuf/duration.proto. This is about 10,000 years in seconds.
- maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
- minSeconds = -maxSeconds
-)
-
-// validateDuration determines whether the durpb.Duration is valid according to the
-// definition in google/protobuf/duration.proto. A valid durpb.Duration
-// may still be too large to fit into a time.Duration (the range of durpb.Duration
-// is about 10,000 years, and the range of time.Duration is about 290).
-func validateDuration(d *durpb.Duration) error {
- if d == nil {
- return errors.New("duration: nil Duration")
- }
- if d.Seconds < minSeconds || d.Seconds > maxSeconds {
- return fmt.Errorf("duration: %v: seconds out of range", d)
- }
- if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
- return fmt.Errorf("duration: %v: nanos out of range", d)
- }
- // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
- if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
- return fmt.Errorf("duration: %v: seconds and nanos have different signs", d)
- }
- return nil
-}
-
-// Duration converts a durpb.Duration to a time.Duration. Duration
-// returns an error if the durpb.Duration is invalid or is too large to be
-// represented in a time.Duration.
-func Duration(p *durpb.Duration) (time.Duration, error) {
- if err := validateDuration(p); err != nil {
- return 0, err
- }
- d := time.Duration(p.Seconds) * time.Second
- if int64(d/time.Second) != p.Seconds {
- return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
- }
- if p.Nanos != 0 {
- d += time.Duration(p.Nanos) * time.Nanosecond
- if (d < 0) != (p.Nanos < 0) {
- return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
- }
- }
- return d, nil
-}
-
-// DurationProto converts a time.Duration to a durpb.Duration.
-func DurationProto(d time.Duration) *durpb.Duration {
- nanos := d.Nanoseconds()
- secs := nanos / 1e9
- nanos -= secs * 1e9
- return &durpb.Duration{
- Seconds: secs,
- Nanos: int32(nanos),
- }
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
deleted file mode 100644
index 0d681ee..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/duration.proto
-
-package duration
-
-import (
- fmt "fmt"
- proto "github.com/golang/protobuf/proto"
- math "math"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
-
-// A Duration represents a signed, fixed-length span of time represented
-// as a count of seconds and fractions of seconds at nanosecond
-// resolution. It is independent of any calendar and concepts like "day"
-// or "month". It is related to Timestamp in that the difference between
-// two Timestamp values is a Duration and it can be added or subtracted
-// from a Timestamp. Range is approximately +-10,000 years.
-//
-// # Examples
-//
-// Example 1: Compute Duration from two Timestamps in pseudo code.
-//
-// Timestamp start = ...;
-// Timestamp end = ...;
-// Duration duration = ...;
-//
-// duration.seconds = end.seconds - start.seconds;
-// duration.nanos = end.nanos - start.nanos;
-//
-// if (duration.seconds < 0 && duration.nanos > 0) {
-// duration.seconds += 1;
-// duration.nanos -= 1000000000;
-// } else if (durations.seconds > 0 && duration.nanos < 0) {
-// duration.seconds -= 1;
-// duration.nanos += 1000000000;
-// }
-//
-// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
-//
-// Timestamp start = ...;
-// Duration duration = ...;
-// Timestamp end = ...;
-//
-// end.seconds = start.seconds + duration.seconds;
-// end.nanos = start.nanos + duration.nanos;
-//
-// if (end.nanos < 0) {
-// end.seconds -= 1;
-// end.nanos += 1000000000;
-// } else if (end.nanos >= 1000000000) {
-// end.seconds += 1;
-// end.nanos -= 1000000000;
-// }
-//
-// Example 3: Compute Duration from datetime.timedelta in Python.
-//
-// td = datetime.timedelta(days=3, minutes=10)
-// duration = Duration()
-// duration.FromTimedelta(td)
-//
-// # JSON Mapping
-//
-// In JSON format, the Duration type is encoded as a string rather than an
-// object, where the string ends in the suffix "s" (indicating seconds) and
-// is preceded by the number of seconds, with nanoseconds expressed as
-// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
-// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
-// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
-// microsecond should be expressed in JSON format as "3.000001s".
-//
-//
-type Duration struct {
- // Signed seconds of the span of time. Must be from -315,576,000,000
- // to +315,576,000,000 inclusive. Note: these bounds are computed from:
- // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
- Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
- // Signed fractions of a second at nanosecond resolution of the span
- // of time. Durations less than one second are represented with a 0
- // `seconds` field and a positive or negative `nanos` field. For durations
- // of one second or more, a non-zero value for the `nanos` field must be
- // of the same sign as the `seconds` field. Must be from -999,999,999
- // to +999,999,999 inclusive.
- Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Duration) Reset() { *m = Duration{} }
-func (m *Duration) String() string { return proto.CompactTextString(m) }
-func (*Duration) ProtoMessage() {}
-func (*Duration) Descriptor() ([]byte, []int) {
- return fileDescriptor_23597b2ebd7ac6c5, []int{0}
-}
-
-func (*Duration) XXX_WellKnownType() string { return "Duration" }
-
-func (m *Duration) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Duration.Unmarshal(m, b)
-}
-func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Duration.Marshal(b, m, deterministic)
-}
-func (m *Duration) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Duration.Merge(m, src)
-}
-func (m *Duration) XXX_Size() int {
- return xxx_messageInfo_Duration.Size(m)
-}
-func (m *Duration) XXX_DiscardUnknown() {
- xxx_messageInfo_Duration.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Duration proto.InternalMessageInfo
-
-func (m *Duration) GetSeconds() int64 {
- if m != nil {
- return m.Seconds
- }
- return 0
-}
-
-func (m *Duration) GetNanos() int32 {
- if m != nil {
- return m.Nanos
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
-}
-
-func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_23597b2ebd7ac6c5) }
-
-var fileDescriptor_23597b2ebd7ac6c5 = []byte{
- // 190 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a,
- 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56,
- 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5,
- 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e,
- 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c,
- 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56,
- 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e,
- 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4,
- 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78,
- 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63,
- 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
deleted file mode 100644
index 975fce4..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
+++ /dev/null
@@ -1,117 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/duration";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DurationProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// A Duration represents a signed, fixed-length span of time represented
-// as a count of seconds and fractions of seconds at nanosecond
-// resolution. It is independent of any calendar and concepts like "day"
-// or "month". It is related to Timestamp in that the difference between
-// two Timestamp values is a Duration and it can be added or subtracted
-// from a Timestamp. Range is approximately +-10,000 years.
-//
-// # Examples
-//
-// Example 1: Compute Duration from two Timestamps in pseudo code.
-//
-// Timestamp start = ...;
-// Timestamp end = ...;
-// Duration duration = ...;
-//
-// duration.seconds = end.seconds - start.seconds;
-// duration.nanos = end.nanos - start.nanos;
-//
-// if (duration.seconds < 0 && duration.nanos > 0) {
-// duration.seconds += 1;
-// duration.nanos -= 1000000000;
-// } else if (durations.seconds > 0 && duration.nanos < 0) {
-// duration.seconds -= 1;
-// duration.nanos += 1000000000;
-// }
-//
-// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
-//
-// Timestamp start = ...;
-// Duration duration = ...;
-// Timestamp end = ...;
-//
-// end.seconds = start.seconds + duration.seconds;
-// end.nanos = start.nanos + duration.nanos;
-//
-// if (end.nanos < 0) {
-// end.seconds -= 1;
-// end.nanos += 1000000000;
-// } else if (end.nanos >= 1000000000) {
-// end.seconds += 1;
-// end.nanos -= 1000000000;
-// }
-//
-// Example 3: Compute Duration from datetime.timedelta in Python.
-//
-// td = datetime.timedelta(days=3, minutes=10)
-// duration = Duration()
-// duration.FromTimedelta(td)
-//
-// # JSON Mapping
-//
-// In JSON format, the Duration type is encoded as a string rather than an
-// object, where the string ends in the suffix "s" (indicating seconds) and
-// is preceded by the number of seconds, with nanoseconds expressed as
-// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
-// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
-// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
-// microsecond should be expressed in JSON format as "3.000001s".
-//
-//
-message Duration {
-
- // Signed seconds of the span of time. Must be from -315,576,000,000
- // to +315,576,000,000 inclusive. Note: these bounds are computed from:
- // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
- int64 seconds = 1;
-
- // Signed fractions of a second at nanosecond resolution of the span
- // of time. Durations less than one second are represented with a 0
- // `seconds` field and a positive or negative `nanos` field. For durations
- // of one second or more, a non-zero value for the `nanos` field must be
- // of the same sign as the `seconds` field. Must be from -999,999,999
- // to +999,999,999 inclusive.
- int32 nanos = 2;
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
deleted file mode 100644
index 8da0df0..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go
+++ /dev/null
@@ -1,132 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-package ptypes
-
-// This file implements operations on google.protobuf.Timestamp.
-
-import (
- "errors"
- "fmt"
- "time"
-
- tspb "github.com/golang/protobuf/ptypes/timestamp"
-)
-
-const (
- // Seconds field of the earliest valid Timestamp.
- // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
- minValidSeconds = -62135596800
- // Seconds field just after the latest valid Timestamp.
- // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
- maxValidSeconds = 253402300800
-)
-
-// validateTimestamp determines whether a Timestamp is valid.
-// A valid timestamp represents a time in the range
-// [0001-01-01, 10000-01-01) and has a Nanos field
-// in the range [0, 1e9).
-//
-// If the Timestamp is valid, validateTimestamp returns nil.
-// Otherwise, it returns an error that describes
-// the problem.
-//
-// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
-func validateTimestamp(ts *tspb.Timestamp) error {
- if ts == nil {
- return errors.New("timestamp: nil Timestamp")
- }
- if ts.Seconds < minValidSeconds {
- return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
- }
- if ts.Seconds >= maxValidSeconds {
- return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
- }
- if ts.Nanos < 0 || ts.Nanos >= 1e9 {
- return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
- }
- return nil
-}
-
-// Timestamp converts a google.protobuf.Timestamp proto to a time.Time.
-// It returns an error if the argument is invalid.
-//
-// Unlike most Go functions, if Timestamp returns an error, the first return value
-// is not the zero time.Time. Instead, it is the value obtained from the
-// time.Unix function when passed the contents of the Timestamp, in the UTC
-// locale. This may or may not be a meaningful time; many invalid Timestamps
-// do map to valid time.Times.
-//
-// A nil Timestamp returns an error. The first return value in that case is
-// undefined.
-func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
- // Don't return the zero value on error, because corresponds to a valid
- // timestamp. Instead return whatever time.Unix gives us.
- var t time.Time
- if ts == nil {
- t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
- } else {
- t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
- }
- return t, validateTimestamp(ts)
-}
-
-// TimestampNow returns a google.protobuf.Timestamp for the current time.
-func TimestampNow() *tspb.Timestamp {
- ts, err := TimestampProto(time.Now())
- if err != nil {
- panic("ptypes: time.Now() out of Timestamp range")
- }
- return ts
-}
-
-// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
-// It returns an error if the resulting Timestamp is invalid.
-func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
- ts := &tspb.Timestamp{
- Seconds: t.Unix(),
- Nanos: int32(t.Nanosecond()),
- }
- if err := validateTimestamp(ts); err != nil {
- return nil, err
- }
- return ts, nil
-}
-
-// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
-// Timestamps, it returns an error message in parentheses.
-func TimestampString(ts *tspb.Timestamp) string {
- t, err := Timestamp(ts)
- if err != nil {
- return fmt.Sprintf("(%v)", err)
- }
- return t.Format(time.RFC3339Nano)
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
deleted file mode 100644
index 31cd846..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
+++ /dev/null
@@ -1,179 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/timestamp.proto
-
-package timestamp
-
-import (
- fmt "fmt"
- proto "github.com/golang/protobuf/proto"
- math "math"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
-
-// A Timestamp represents a point in time independent of any time zone
-// or calendar, represented as seconds and fractions of seconds at
-// nanosecond resolution in UTC Epoch time. It is encoded using the
-// Proleptic Gregorian Calendar which extends the Gregorian calendar
-// backwards to year one. It is encoded assuming all minutes are 60
-// seconds long, i.e. leap seconds are "smeared" so that no leap second
-// table is needed for interpretation. Range is from
-// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
-// By restricting to that range, we ensure that we can convert to
-// and from RFC 3339 date strings.
-// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
-//
-// # Examples
-//
-// Example 1: Compute Timestamp from POSIX `time()`.
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(time(NULL));
-// timestamp.set_nanos(0);
-//
-// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
-//
-// struct timeval tv;
-// gettimeofday(&tv, NULL);
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(tv.tv_sec);
-// timestamp.set_nanos(tv.tv_usec * 1000);
-//
-// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
-//
-// FILETIME ft;
-// GetSystemTimeAsFileTime(&ft);
-// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-//
-// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
-// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
-// Timestamp timestamp;
-// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
-// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
-//
-// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
-//
-// long millis = System.currentTimeMillis();
-//
-// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
-// .setNanos((int) ((millis % 1000) * 1000000)).build();
-//
-//
-// Example 5: Compute Timestamp from current time in Python.
-//
-// timestamp = Timestamp()
-// timestamp.GetCurrentTime()
-//
-// # JSON Mapping
-//
-// In JSON format, the Timestamp type is encoded as a string in the
-// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
-// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
-// where {year} is always expressed using four digits while {month}, {day},
-// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
-// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
-// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
-// is required. A proto3 JSON serializer should always use UTC (as indicated by
-// "Z") when printing the Timestamp type and a proto3 JSON parser should be
-// able to accept both UTC and other timezones (as indicated by an offset).
-//
-// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
-// 01:30 UTC on January 15, 2017.
-//
-// In JavaScript, one can convert a Date object to this format using the
-// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
-// method. In Python, a standard `datetime.datetime` object can be converted
-// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
-// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
-// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
-// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--
-// ) to obtain a formatter capable of generating timestamps in this format.
-//
-//
-type Timestamp struct {
- // Represents seconds of UTC time since Unix epoch
- // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
- // 9999-12-31T23:59:59Z inclusive.
- Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
- // Non-negative fractions of a second at nanosecond resolution. Negative
- // second values with fractions must still have non-negative nanos values
- // that count forward in time. Must be from 0 to 999,999,999
- // inclusive.
- Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Timestamp) Reset() { *m = Timestamp{} }
-func (m *Timestamp) String() string { return proto.CompactTextString(m) }
-func (*Timestamp) ProtoMessage() {}
-func (*Timestamp) Descriptor() ([]byte, []int) {
- return fileDescriptor_292007bbfe81227e, []int{0}
-}
-
-func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
-
-func (m *Timestamp) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_Timestamp.Unmarshal(m, b)
-}
-func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic)
-}
-func (m *Timestamp) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Timestamp.Merge(m, src)
-}
-func (m *Timestamp) XXX_Size() int {
- return xxx_messageInfo_Timestamp.Size(m)
-}
-func (m *Timestamp) XXX_DiscardUnknown() {
- xxx_messageInfo_Timestamp.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Timestamp proto.InternalMessageInfo
-
-func (m *Timestamp) GetSeconds() int64 {
- if m != nil {
- return m.Seconds
- }
- return 0
-}
-
-func (m *Timestamp) GetNanos() int32 {
- if m != nil {
- return m.Nanos
- }
- return 0
-}
-
-func init() {
- proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
-}
-
-func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_292007bbfe81227e) }
-
-var fileDescriptor_292007bbfe81227e = []byte{
- // 191 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f,
- 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d,
- 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28,
- 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5,
- 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89,
- 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70,
- 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51,
- 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89,
- 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71,
- 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a,
- 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43,
- 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
deleted file mode 100644
index eafb3fa..0000000
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
+++ /dev/null
@@ -1,135 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "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 THE COPYRIGHT
-// OWNER OR CONTRIBUTORS 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.
-
-syntax = "proto3";
-
-package google.protobuf;
-
-option csharp_namespace = "Google.Protobuf.WellKnownTypes";
-option cc_enable_arenas = true;
-option go_package = "github.com/golang/protobuf/ptypes/timestamp";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "TimestampProto";
-option java_multiple_files = true;
-option objc_class_prefix = "GPB";
-
-// A Timestamp represents a point in time independent of any time zone
-// or calendar, represented as seconds and fractions of seconds at
-// nanosecond resolution in UTC Epoch time. It is encoded using the
-// Proleptic Gregorian Calendar which extends the Gregorian calendar
-// backwards to year one. It is encoded assuming all minutes are 60
-// seconds long, i.e. leap seconds are "smeared" so that no leap second
-// table is needed for interpretation. Range is from
-// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
-// By restricting to that range, we ensure that we can convert to
-// and from RFC 3339 date strings.
-// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
-//
-// # Examples
-//
-// Example 1: Compute Timestamp from POSIX `time()`.
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(time(NULL));
-// timestamp.set_nanos(0);
-//
-// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
-//
-// struct timeval tv;
-// gettimeofday(&tv, NULL);
-//
-// Timestamp timestamp;
-// timestamp.set_seconds(tv.tv_sec);
-// timestamp.set_nanos(tv.tv_usec * 1000);
-//
-// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
-//
-// FILETIME ft;
-// GetSystemTimeAsFileTime(&ft);
-// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-//
-// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
-// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
-// Timestamp timestamp;
-// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
-// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
-//
-// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
-//
-// long millis = System.currentTimeMillis();
-//
-// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
-// .setNanos((int) ((millis % 1000) * 1000000)).build();
-//
-//
-// Example 5: Compute Timestamp from current time in Python.
-//
-// timestamp = Timestamp()
-// timestamp.GetCurrentTime()
-//
-// # JSON Mapping
-//
-// In JSON format, the Timestamp type is encoded as a string in the
-// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
-// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
-// where {year} is always expressed using four digits while {month}, {day},
-// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
-// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
-// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
-// is required. A proto3 JSON serializer should always use UTC (as indicated by
-// "Z") when printing the Timestamp type and a proto3 JSON parser should be
-// able to accept both UTC and other timezones (as indicated by an offset).
-//
-// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
-// 01:30 UTC on January 15, 2017.
-//
-// In JavaScript, one can convert a Date object to this format using the
-// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
-// method. In Python, a standard `datetime.datetime` object can be converted
-// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
-// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
-// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
-// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--
-// ) to obtain a formatter capable of generating timestamps in this format.
-//
-//
-message Timestamp {
-
- // Represents seconds of UTC time since Unix epoch
- // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
- // 9999-12-31T23:59:59Z inclusive.
- int64 seconds = 1;
-
- // Non-negative fractions of a second at nanosecond resolution. Negative
- // second values with fractions must still have non-negative nanos values
- // that count forward in time. Must be from 0 to 999,999,999
- // inclusive.
- int32 nanos = 2;
-}
diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE b/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE
deleted file mode 100644
index 14127cd..0000000
--- a/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE
+++ /dev/null
@@ -1,9 +0,0 @@
-(The MIT License)
-
-Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de)
-
-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.
diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
deleted file mode 100644
index 949b77e..0000000
--- a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
+++ /dev/null
@@ -1,40 +0,0 @@
-# Windows Terminal Sequences
-
-This library allow for enabling Windows terminal color support for Go.
-
-See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details.
-
-## Usage
-
-```go
-import (
- "syscall"
-
- sequences "github.com/konsorten/go-windows-terminal-sequences"
-)
-
-func main() {
- sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true)
-}
-
-```
-
-## Authors
-
-The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de).
-
-We thank all the authors who provided code to this library:
-
-* Felix Kollmann
-
-## License
-
-(The MIT License)
-
-Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de)
-
-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.
diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod b/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod
deleted file mode 100644
index 716c613..0000000
--- a/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod
+++ /dev/null
@@ -1 +0,0 @@
-module github.com/konsorten/go-windows-terminal-sequences
diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
deleted file mode 100644
index ef18d8f..0000000
--- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// +build windows
-
-package sequences
-
-import (
- "syscall"
- "unsafe"
-)
-
-var (
- kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll")
- setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode")
-)
-
-func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error {
- const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4
-
- var mode uint32
- err := syscall.GetConsoleMode(syscall.Stdout, &mode)
- if err != nil {
- return err
- }
-
- if enable {
- mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
- } else {
- mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING
- }
-
- ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode))
- if ret == 0 {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/mattn/go-sqlite3/.gitignore b/vendor/github.com/mattn/go-sqlite3/.gitignore
deleted file mode 100644
index fa0e6b5..0000000
--- a/vendor/github.com/mattn/go-sqlite3/.gitignore
+++ /dev/null
@@ -1,14 +0,0 @@
-*.db
-*.exe
-*.dll
-*.o
-
-# VSCode
-.vscode
-
-# Exclude from upgrade
-upgrade/*.c
-upgrade/*.h
-
-# Exclude upgrade binary
-upgrade/upgrade
diff --git a/vendor/github.com/mattn/go-sqlite3/.travis.yml b/vendor/github.com/mattn/go-sqlite3/.travis.yml
deleted file mode 100644
index eb0abbb..0000000
--- a/vendor/github.com/mattn/go-sqlite3/.travis.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-language: go
-
-os:
- - linux
- - osx
-
-addons:
- apt:
- update: true
-
-go:
- - 1.9.x
- - 1.10.x
- - 1.11.x
- - master
-
-before_install:
- - |
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
- brew update
- fi
- - go get github.com/smartystreets/goconvey
- - go get github.com/mattn/goveralls
- - go get golang.org/x/tools/cmd/cover
-
-script:
- - $HOME/gopath/bin/goveralls -repotoken 3qJVUE0iQwqnCbmNcDsjYu1nh4J4KIFXx
- - go test -race -v . -tags ""
- - go test -race -v . -tags "libsqlite3"
- - go test -race -v . -tags "sqlite_allow_uri_authority sqlite_app_armor sqlite_foreign_keys sqlite_fts5 sqlite_icu sqlite_introspect sqlite_json sqlite_secure_delete sqlite_see sqlite_stat4 sqlite_trace sqlite_userauth sqlite_vacuum_incr sqlite_vtable sqlite_unlock_notify"
- - go test -race -v . -tags "sqlite_vacuum_full"
\ No newline at end of file
diff --git a/vendor/github.com/mattn/go-sqlite3/LICENSE b/vendor/github.com/mattn/go-sqlite3/LICENSE
deleted file mode 100644
index ca458bb..0000000
--- a/vendor/github.com/mattn/go-sqlite3/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Yasuhiro Matsumoto
-
-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.
diff --git a/vendor/github.com/mattn/go-sqlite3/README.md b/vendor/github.com/mattn/go-sqlite3/README.md
deleted file mode 100644
index 8a87941..0000000
--- a/vendor/github.com/mattn/go-sqlite3/README.md
+++ /dev/null
@@ -1,521 +0,0 @@
-go-sqlite3
-==========
-
-[](http://godoc.org/github.com/mattn/go-sqlite3)
-[](https://travis-ci.org/mattn/go-sqlite3)
-[](https://coveralls.io/r/mattn/go-sqlite3?branch=master)
-[](https://goreportcard.com/report/github.com/mattn/go-sqlite3)
-
-# Description
-
-sqlite3 driver conforming to the built-in database/sql interface
-
-Supported Golang version: See .travis.yml
-
-[This package follows the official Golang Release Policy.](https://golang.org/doc/devel/release.html#policy)
-
-### Overview
-
-- [Installation](#installation)
-- [API Reference](#api-reference)
-- [Connection String](#connection-string)
-- [Features](#features)
-- [Compilation](#compilation)
- - [Android](#android)
- - [ARM](#arm)
- - [Cross Compile](#cross-compile)
- - [Google Cloud Platform](#google-cloud-platform)
- - [Linux](#linux)
- - [Alpine](#alpine)
- - [Fedora](#fedora)
- - [Ubuntu](#ubuntu)
- - [Mac OSX](#mac-osx)
- - [Windows](#windows)
- - [Errors](#errors)
-- [User Authentication](#user-authentication)
- - [Compile](#compile)
- - [Usage](#usage)
-- [Extensions](#extensions)
- - [Spatialite](#spatialite)
-- [FAQ](#faq)
-- [License](#license)
-
-# Installation
-
-This package can be installed with the go get command:
-
- go get github.com/mattn/go-sqlite3
-
-_go-sqlite3_ is *cgo* package.
-If you want to build your app using go-sqlite3, you need gcc.
-However, after you have built and installed _go-sqlite3_ with `go install github.com/mattn/go-sqlite3` (which requires gcc), you can build your app without relying on gcc in future.
-
-***Important: because this is a `CGO` enabled package you are required to set the environment variable `CGO_ENABLED=1` and have a `gcc` compile present within your path.***
-
-# API Reference
-
-API documentation can be found here: http://godoc.org/github.com/mattn/go-sqlite3
-
-Examples can be found under the [examples](./_example) directory
-
-# Connection String
-
-When creating a new SQLite database or connection to an existing one, with the file name additional options can be given.
-This is also known as a DSN string. (Data Source Name).
-
-Options are append after the filename of the SQLite database.
-The database filename and options are seperated by an `?` (Question Mark).
-Options should be URL-encoded (see [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)).
-
-This also applies when using an in-memory database instead of a file.
-
-Options can be given using the following format: `KEYWORD=VALUE` and multiple options can be combined with the `&` ampersand.
-
-This library supports dsn options of SQLite itself and provides additional options.
-
-Boolean values can be one of:
-* `0` `no` `false` `off`
-* `1` `yes` `true` `on`
-
-| Name | Key | Value(s) | Description |
-|------|-----|----------|-------------|
-| UA - Create | `_auth` | - | Create User Authentication, for more information see [User Authentication](#user-authentication) |
-| UA - Username | `_auth_user` | `string` | Username for User Authentication, for more information see [User Authentication](#user-authentication) |
-| UA - Password | `_auth_pass` | `string` | Password for User Authentication, for more information see [User Authentication](#user-authentication) |
-| UA - Crypt | `_auth_crypt` | - SHA1
- SSHA1
- SHA256
- SSHA256
- SHA384
- SSHA384
- SHA512
- SSHA512
| Password encoder to use for User Authentication, for more information see [User Authentication](#user-authentication) |
-| UA - Salt | `_auth_salt` | `string` | Salt to use if the configure password encoder requires a salt, for User Authentication, for more information see [User Authentication](#user-authentication) |
-| Auto Vacuum | `_auto_vacuum` \| `_vacuum` | - `0` \| `none`
- `1` \| `full`
- `2` \| `incremental`
| For more information see [PRAGMA auto_vacuum](https://www.sqlite.org/pragma.html#pragma_auto_vacuum) |
-| Busy Timeout | `_busy_timeout` \| `_timeout` | `int` | Specify value for sqlite3_busy_timeout. For more information see [PRAGMA busy_timeout](https://www.sqlite.org/pragma.html#pragma_busy_timeout) |
-| Case Sensitive LIKE | `_case_sensitive_like` \| `_cslike` | `boolean` | For more information see [PRAGMA case_sensitive_like](https://www.sqlite.org/pragma.html#pragma_case_sensitive_like) |
-| Defer Foreign Keys | `_defer_foreign_keys` \| `_defer_fk` | `boolean` | For more information see [PRAGMA defer_foreign_keys](https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys) |
-| Foreign Keys | `_foreign_keys` \| `_fk` | `boolean` | For more information see [PRAGMA foreign_keys](https://www.sqlite.org/pragma.html#pragma_foreign_keys) |
-| Ignore CHECK Constraints | `_ignore_check_constraints` | `boolean` | For more information see [PRAGMA ignore_check_constraints](https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints) |
-| Immutable | `immutable` | `boolean` | For more information see [Immutable](https://www.sqlite.org/c3ref/open.html) |
-| Journal Mode | `_journal_mode` \| `_journal` | - DELETE
- TRUNCATE
- PERSIST
- MEMORY
- WAL
- OFF
| For more information see [PRAGMA journal_mode](https://www.sqlite.org/pragma.html#pragma_journal_mode) |
-| Locking Mode | `_locking_mode` \| `_locking` | | For more information see [PRAGMA locking_mode](https://www.sqlite.org/pragma.html#pragma_locking_mode) |
-| Mode | `mode` | | Access Mode of the database. For more information see [SQLite Open](https://www.sqlite.org/c3ref/open.html) |
-| Mutex Locking | `_mutex` | | Specify mutex mode. |
-| Query Only | `_query_only` | `boolean` | For more information see [PRAGMA query_only](https://www.sqlite.org/pragma.html#pragma_query_only) |
-| Recursive Triggers | `_recursive_triggers` \| `_rt` | `boolean` | For more information see [PRAGMA recursive_triggers](https://www.sqlite.org/pragma.html#pragma_recursive_triggers) |
-| Secure Delete | `_secure_delete` | `boolean` \| `FAST` | For more information see [PRAGMA secure_delete](https://www.sqlite.org/pragma.html#pragma_secure_delete) |
-| Shared-Cache Mode | `cache` | | Set cache mode for more information see [sqlite.org](https://www.sqlite.org/sharedcache.html) |
-| Synchronous | `_synchronous` \| `_sync` | - 0 \| OFF
- 1 \| NORMAL
- 2 \| FULL
- 3 \| EXTRA
| For more information see [PRAGMA synchronous](https://www.sqlite.org/pragma.html#pragma_synchronous) |
-| Time Zone Location | `_loc` | auto | Specify location of time format. |
-| Transaction Lock | `_txlock` | - immediate
- deferred
- exclusive
| Specify locking behavior for transactions. |
-| Writable Schema | `_writable_schema` | `Boolean` | When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file. |
-
-## DSN Examples
-
-```
-file:test.db?cache=shared&mode=memory
-```
-
-# Features
-
-This package allows additional configuration of features available within SQLite3 to be enabled or disabled by golang build constraints also known as build `tags`.
-
-[Click here for more information about build tags / constraints.](https://golang.org/pkg/go/build/#hdr-Build_Constraints)
-
-### Usage
-
-If you wish to build this library with additional extensions / features.
-Use the following command.
-
-```bash
-go build --tags ""
-```
-
-For available features see the extension list.
-When using multiple build tags, all the different tags should be space delimted.
-
-Example:
-
-```bash
-go build --tags "icu json1 fts5 secure_delete"
-```
-
-### Feature / Extension List
-
-| Extension | Build Tag | Description |
-|-----------|-----------|-------------|
-| Additional Statistics | sqlite_stat4 | This option adds additional logic to the ANALYZE command and to the query planner that can help SQLite to chose a better query plan under certain situations. The ANALYZE command is enhanced to collect histogram data from all columns of every index and store that data in the sqlite_stat4 table.
The query planner will then use the histogram data to help it make better index choices. The downside of this compile-time option is that it violates the query planner stability guarantee making it more difficult to ensure consistent performance in mass-produced applications.
SQLITE_ENABLE_STAT4 is an enhancement of SQLITE_ENABLE_STAT3. STAT3 only recorded histogram data for the left-most column of each index whereas the STAT4 enhancement records histogram data from all columns of each index.
The SQLITE_ENABLE_STAT3 compile-time option is a no-op and is ignored if the SQLITE_ENABLE_STAT4 compile-time option is used |
-| Allow URI Authority | sqlite_allow_uri_authority | URI filenames normally throws an error if the authority section is not either empty or "localhost".
However, if SQLite is compiled with the SQLITE_ALLOW_URI_AUTHORITY compile-time option, then the URI is converted into a Uniform Naming Convention (UNC) filename and passed down to the underlying operating system that way |
-| App Armor | sqlite_app_armor | When defined, this C-preprocessor macro activates extra code that attempts to detect misuse of the SQLite API, such as passing in NULL pointers to required parameters or using objects after they have been destroyed.
App Armor is not available under `Windows`. |
-| Disable Load Extensions | sqlite_omit_load_extension | Loading of external extensions is enabled by default.
To disable extension loading add the build tag `sqlite_omit_load_extension`. |
-| Foreign Keys | sqlite_foreign_keys | This macro determines whether enforcement of foreign key constraints is enabled or disabled by default for new database connections.
Each database connection can always turn enforcement of foreign key constraints on and off and run-time using the foreign_keys pragma.
Enforcement of foreign key constraints is normally off by default, but if this compile-time parameter is set to 1, enforcement of foreign key constraints will be on by default |
-| Full Auto Vacuum | sqlite_vacuum_full | Set the default auto vacuum to full |
-| Incremental Auto Vacuum | sqlite_vacuum_incr | Set the default auto vacuum to incremental |
-| Full Text Search Engine | sqlite_fts5 | When this option is defined in the amalgamation, versions 5 of the full-text search engine (fts5) is added to the build automatically |
-| International Components for Unicode | sqlite_icu | This option causes the International Components for Unicode or "ICU" extension to SQLite to be added to the build |
-| Introspect PRAGMAS | sqlite_introspect | This option adds some extra PRAGMA statements. - PRAGMA function_list
- PRAGMA module_list
- PRAGMA pragma_list
|
-| JSON SQL Functions | sqlite_json | When this option is defined in the amalgamation, the JSON SQL functions are added to the build automatically |
-| Secure Delete | sqlite_secure_delete | This compile-time option changes the default setting of the secure_delete pragma.
When this option is not used, secure_delete defaults to off. When this option is present, secure_delete defaults to on.
The secure_delete setting causes deleted content to be overwritten with zeros. There is a small performance penalty since additional I/O must occur.
On the other hand, secure_delete can prevent fragments of sensitive information from lingering in unused parts of the database file after it has been deleted. See the documentation on the secure_delete pragma for additional information |
-| Secure Delete (FAST) | sqlite_secure_delete_fast | For more information see [PRAGMA secure_delete](https://www.sqlite.org/pragma.html#pragma_secure_delete) |
-| Tracing / Debug | sqlite_trace | Activate trace functions |
-| User Authentication | sqlite_userauth | SQLite User Authentication see [User Authentication](#user-authentication) for more information. |
-
-# Compilation
-
-This package requires `CGO_ENABLED=1` ennvironment variable if not set by default, and the presence of the `gcc` compiler.
-
-If you need to add additional CFLAGS or LDFLAGS to the build command, and do not want to modify this package. Then this can be achieved by using the `CGO_CFLAGS` and `CGO_LDFLAGS` environment variables.
-
-## Android
-
-This package can be compiled for android.
-Compile with:
-
-```bash
-go build --tags "android"
-```
-
-For more information see [#201](https://github.com/mattn/go-sqlite3/issues/201)
-
-# ARM
-
-To compile for `ARM` use the following environment.
-
-```bash
-env CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \
- CGO_ENABLED=1 GOOS=linux GOARCH=arm GOARM=7 \
- go build -v
-```
-
-Additional information:
-- [#242](https://github.com/mattn/go-sqlite3/issues/242)
-- [#504](https://github.com/mattn/go-sqlite3/issues/504)
-
-# Cross Compile
-
-This library can be cross-compiled.
-
-In some cases you are required to the `CC` environment variable with the cross compiler.
-
-Additional information:
-- [#491](https://github.com/mattn/go-sqlite3/issues/491)
-- [#560](https://github.com/mattn/go-sqlite3/issues/560)
-
-# Google Cloud Platform
-
-Building on GCP is not possible because Google Cloud Platform does not allow `gcc` to be executed.
-
-Please work only with compiled final binaries.
-
-## Linux
-
-To compile this package on Linux you must install the development tools for your linux distribution.
-
-To compile under linux use the build tag `linux`.
-
-```bash
-go build --tags "linux"
-```
-
-If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag.
-
-```
-go build --tags "libsqlite3 linux"
-```
-
-### Alpine
-
-When building in an `alpine` container run the following command before building.
-
-```
-apk add --update gcc musl-dev
-```
-
-### Fedora
-
-```bash
-sudo yum groupinstall "Development Tools" "Development Libraries"
-```
-
-### Ubuntu
-
-```bash
-sudo apt-get install build-essential
-```
-
-## Mac OSX
-
-OSX should have all the tools present to compile this package, if not install XCode this will add all the developers tools.
-
-Required dependency
-
-```bash
-brew install sqlite3
-```
-
-For OSX there is an additional package install which is required if you wish to build the `icu` extension.
-
-This additional package can be installed with `homebrew`.
-
-```bash
-brew upgrade icu4c
-```
-
-To compile for Mac OSX.
-
-```bash
-go build --tags "darwin"
-```
-
-If you wish to link directly to libsqlite3 then you can use the `libsqlite3` build tag.
-
-```
-go build --tags "libsqlite3 darwin"
-```
-
-Additional information:
-- [#206](https://github.com/mattn/go-sqlite3/issues/206)
-- [#404](https://github.com/mattn/go-sqlite3/issues/404)
-
-## Windows
-
-To compile this package on Windows OS you must have the `gcc` compiler installed.
-
-1) Install a Windows `gcc` toolchain.
-2) Add the `bin` folders to the Windows path if the installer did not do this by default.
-3) Open a terminal for the TDM-GCC toolchain, can be found in the Windows Start menu.
-4) Navigate to your project folder and run the `go build ...` command for this package.
-
-For example the TDM-GCC Toolchain can be found [here](https://sourceforge.net/projects/tdm-gcc/).
-
-## Errors
-
-- Compile error: `can not be used when making a shared object; recompile with -fPIC`
-
- When receiving a compile time error referencing recompile with `-FPIC` then you
- are probably using a hardend system.
-
- You can compile the library on a hardend system with the following command.
-
- ```bash
- go build -ldflags '-extldflags=-fno-PIC'
- ```
-
- More details see [#120](https://github.com/mattn/go-sqlite3/issues/120)
-
-- Can't build go-sqlite3 on windows 64bit.
-
- > Probably, you are using go 1.0, go1.0 has a problem when it comes to compiling/linking on windows 64bit.
- > See: [#27](https://github.com/mattn/go-sqlite3/issues/27)
-
-- `go get github.com/mattn/go-sqlite3` throws compilation error.
-
- `gcc` throws: `internal compiler error`
-
- Remove the download repository from your disk and try re-install with:
-
- ```bash
- go install github.com/mattn/go-sqlite3
- ```
-
-# User Authentication
-
-This package supports the SQLite User Authentication module.
-
-## Compile
-
-To use the User authentication module the package has to be compiled with the tag `sqlite_userauth`. See [Features](#features).
-
-## Usage
-
-### Create protected database
-
-To create a database protected by user authentication provide the following argument to the connection string `_auth`.
-This will enable user authentication within the database. This option however requires two additional arguments:
-
-- `_auth_user`
-- `_auth_pass`
-
-When `_auth` is present on the connection string user authentication will be enabled and the provided user will be created
-as an `admin` user. After initial creation, the parameter `_auth` has no effect anymore and can be omitted from the connection string.
-
-Example connection string:
-
-Create an user authentication database with user `admin` and password `admin`.
-
-`file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin`
-
-Create an user authentication database with user `admin` and password `admin` and use `SHA1` for the password encoding.
-
-`file:test.s3db?_auth&_auth_user=admin&_auth_pass=admin&_auth_crypt=sha1`
-
-### Password Encoding
-
-The passwords within the user authentication module of SQLite are encoded with the SQLite function `sqlite_cryp`.
-This function uses a ceasar-cypher which is quite insecure.
-This library provides several additional password encoders which can be configured through the connection string.
-
-The password cypher can be configured with the key `_auth_crypt`. And if the configured password encoder also requires an
-salt this can be configured with `_auth_salt`.
-
-#### Available Encoders
-
-- SHA1
-- SSHA1 (Salted SHA1)
-- SHA256
-- SSHA256 (salted SHA256)
-- SHA384
-- SSHA384 (salted SHA384)
-- SHA512
-- SSHA512 (salted SHA512)
-
-### Restrictions
-
-Operations on the database regarding to user management can only be preformed by an administrator user.
-
-### Support
-
-The user authentication supports two kinds of users
-
-- administrators
-- regular users
-
-### User Management
-
-User management can be done by directly using the `*SQLiteConn` or by SQL.
-
-#### SQL
-
-The following sql functions are available for user management.
-
-| Function | Arguments | Description |
-|----------|-----------|-------------|
-| `authenticate` | username `string`, password `string` | Will authenticate an user, this is done by the connection; and should not be used manually. |
-| `auth_user_add` | username `string`, password `string`, admin `int` | This function will add an user to the database.
if the database is not protected by user authentication it will enable it. Argument `admin` is an integer identifying if the added user should be an administrator. Only Administrators can add administrators. |
-| `auth_user_change` | username `string`, password `string`, admin `int` | Function to modify an user. Users can change their own password, but only an administrator can change the administrator flag. |
-| `authUserDelete` | username `string` | Delete an user from the database. Can only be used by an administrator. The current logged in administrator cannot be deleted. This is to make sure their is always an administrator remaining. |
-
-These functions will return an integer.
-
-- 0 (SQLITE_OK)
-- 23 (SQLITE_AUTH) Failed to perform due to authentication or insufficient privileges
-
-##### Examples
-
-```sql
-// Autheticate user
-// Create Admin User
-SELECT auth_user_add('admin2', 'admin2', 1);
-
-// Change password for user
-SELECT auth_user_change('user', 'userpassword', 0);
-
-// Delete user
-SELECT user_delete('user');
-```
-
-#### *SQLiteConn
-
-The following functions are available for User authentication from the `*SQLiteConn`.
-
-| Function | Description |
-|----------|-------------|
-| `Authenticate(username, password string) error` | Authenticate user |
-| `AuthUserAdd(username, password string, admin bool) error` | Add user |
-| `AuthUserChange(username, password string, admin bool) error` | Modify user |
-| `AuthUserDelete(username string) error` | Delete user |
-
-### Attached database
-
-When using attached databases. SQLite will use the authentication from the `main` database for the attached database(s).
-
-# Extensions
-
-If you want your own extension to be listed here or you want to add a reference to an extension; please submit an Issue for this.
-
-## Spatialite
-
-Spatialite is available as an extension to SQLite, and can be used in combination with this repository.
-For an example see [shaxbee/go-spatialite](https://github.com/shaxbee/go-spatialite).
-
-# FAQ
-
-- Getting insert error while query is opened.
-
- > You can pass some arguments into the connection string, for example, a URI.
- > See: [#39](https://github.com/mattn/go-sqlite3/issues/39)
-
-- Do you want to cross compile? mingw on Linux or Mac?
-
- > See: [#106](https://github.com/mattn/go-sqlite3/issues/106)
- > See also: http://www.limitlessfx.com/cross-compile-golang-app-for-windows-from-linux.html
-
-- Want to get time.Time with current locale
-
- Use `_loc=auto` in SQLite3 filename schema like `file:foo.db?_loc=auto`.
-
-- Can I use this in multiple routines concurrently?
-
- Yes for readonly. But, No for writable. See [#50](https://github.com/mattn/go-sqlite3/issues/50), [#51](https://github.com/mattn/go-sqlite3/issues/51), [#209](https://github.com/mattn/go-sqlite3/issues/209), [#274](https://github.com/mattn/go-sqlite3/issues/274).
-
-- Why I'm getting `no such table` error?
-
- Why is it racy if I use a `sql.Open("sqlite3", ":memory:")` database?
-
- Each connection to `":memory:"` opens a brand new in-memory sql database, so if
- the stdlib's sql engine happens to open another connection and you've only
- specified `":memory:"`, that connection will see a brand new database. A
- workaround is to use `"file::memory:?cache=shared"` (or `"file:foobar?mode=memory&cache=shared"`). Every
- connection to this string will point to the same in-memory database.
-
- Note that if the last database connection in the pool closes, the in-memory database is deleted. Make sure the [max idle connection limit](https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns) is > 0, and the [connection lifetime](https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime) is infinite.
-
- For more information see
- * [#204](https://github.com/mattn/go-sqlite3/issues/204)
- * [#511](https://github.com/mattn/go-sqlite3/issues/511)
- * https://www.sqlite.org/sharedcache.html#shared_cache_and_in_memory_databases
- * https://www.sqlite.org/inmemorydb.html#sharedmemdb
-
-- Reading from database with large amount of goroutines fails on OSX.
-
- OS X limits OS-wide to not have more than 1000 files open simultaneously by default.
-
- For more information see [#289](https://github.com/mattn/go-sqlite3/issues/289)
-
-- Trying to execute a `.` (dot) command throws an error.
-
- Error: `Error: near ".": syntax error`
- Dot command are part of SQLite3 CLI not of this library.
-
- You need to implement the feature or call the sqlite3 cli.
-
- More information see [#305](https://github.com/mattn/go-sqlite3/issues/305)
-
-- Error: `database is locked`
-
- When you get a database is locked. Please use the following options.
-
- Add to DSN: `cache=shared`
-
- Example:
- ```go
- db, err := sql.Open("sqlite3", "file:locked.sqlite?cache=shared")
- ```
-
- Second please set the database connections of the SQL package to 1.
-
- ```go
- db.SetMaxOpenConns(1)
- ```
-
- More information see [#209](https://github.com/mattn/go-sqlite3/issues/209)
-
-# License
-
-MIT: http://mattn.mit-license.org/2018
-
-sqlite3-binding.c, sqlite3-binding.h, sqlite3ext.h
-
-The -binding suffix was added to avoid build failures under gccgo.
-
-In this repository, those files are an amalgamation of code that was copied from SQLite3. The license of that code is the same as the license of SQLite3.
-
-# Author
-
-Yasuhiro Matsumoto (a.k.a mattn)
-
-G.J.R. Timmer
diff --git a/vendor/github.com/mattn/go-sqlite3/backup.go b/vendor/github.com/mattn/go-sqlite3/backup.go
deleted file mode 100644
index 5ab3a54..0000000
--- a/vendor/github.com/mattn/go-sqlite3/backup.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright (C) 2014 Yasuhiro Matsumoto .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package sqlite3
-
-/*
-#ifndef USE_LIBSQLITE3
-#include
-#else
-#include
-#endif
-#include
-*/
-import "C"
-import (
- "runtime"
- "unsafe"
-)
-
-// SQLiteBackup implement interface of Backup.
-type SQLiteBackup struct {
- b *C.sqlite3_backup
-}
-
-// Backup make backup from src to dest.
-func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) {
- destptr := C.CString(dest)
- defer C.free(unsafe.Pointer(destptr))
- srcptr := C.CString(src)
- defer C.free(unsafe.Pointer(srcptr))
-
- if b := C.sqlite3_backup_init(c.db, destptr, conn.db, srcptr); b != nil {
- bb := &SQLiteBackup{b: b}
- runtime.SetFinalizer(bb, (*SQLiteBackup).Finish)
- return bb, nil
- }
- return nil, c.lastError()
-}
-
-// Step to backs up for one step. Calls the underlying `sqlite3_backup_step`
-// function. This function returns a boolean indicating if the backup is done
-// and an error signalling any other error. Done is returned if the underlying
-// C function returns SQLITE_DONE (Code 101)
-func (b *SQLiteBackup) Step(p int) (bool, error) {
- ret := C.sqlite3_backup_step(b.b, C.int(p))
- if ret == C.SQLITE_DONE {
- return true, nil
- } else if ret != 0 && ret != C.SQLITE_LOCKED && ret != C.SQLITE_BUSY {
- return false, Error{Code: ErrNo(ret)}
- }
- return false, nil
-}
-
-// Remaining return whether have the rest for backup.
-func (b *SQLiteBackup) Remaining() int {
- return int(C.sqlite3_backup_remaining(b.b))
-}
-
-// PageCount return count of pages.
-func (b *SQLiteBackup) PageCount() int {
- return int(C.sqlite3_backup_pagecount(b.b))
-}
-
-// Finish close backup.
-func (b *SQLiteBackup) Finish() error {
- return b.Close()
-}
-
-// Close close backup.
-func (b *SQLiteBackup) Close() error {
- ret := C.sqlite3_backup_finish(b.b)
-
- // sqlite3_backup_finish() never fails, it just returns the
- // error code from previous operations, so clean up before
- // checking and returning an error
- b.b = nil
- runtime.SetFinalizer(b, nil)
-
- if ret != 0 {
- return Error{Code: ErrNo(ret)}
- }
- return nil
-}
diff --git a/vendor/github.com/mattn/go-sqlite3/callback.go b/vendor/github.com/mattn/go-sqlite3/callback.go
deleted file mode 100644
index e8c492b..0000000
--- a/vendor/github.com/mattn/go-sqlite3/callback.go
+++ /dev/null
@@ -1,380 +0,0 @@
-// Copyright (C) 2014 Yasuhiro Matsumoto .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package sqlite3
-
-// You can't export a Go function to C and have definitions in the C
-// preamble in the same file, so we have to have callbackTrampoline in
-// its own file. Because we need a separate file anyway, the support
-// code for SQLite custom functions is in here.
-
-/*
-#ifndef USE_LIBSQLITE3
-#include
-#else
-#include
-#endif
-#include
-
-void _sqlite3_result_text(sqlite3_context* ctx, const char* s);
-void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l);
-*/
-import "C"
-
-import (
- "errors"
- "fmt"
- "math"
- "reflect"
- "sync"
- "unsafe"
-)
-
-//export callbackTrampoline
-func callbackTrampoline(ctx *C.sqlite3_context, argc int, argv **C.sqlite3_value) {
- args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
- fi := lookupHandle(uintptr(C.sqlite3_user_data(ctx))).(*functionInfo)
- fi.Call(ctx, args)
-}
-
-//export stepTrampoline
-func stepTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) {
- args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)]
- ai := lookupHandle(uintptr(C.sqlite3_user_data(ctx))).(*aggInfo)
- ai.Step(ctx, args)
-}
-
-//export doneTrampoline
-func doneTrampoline(ctx *C.sqlite3_context) {
- handle := uintptr(C.sqlite3_user_data(ctx))
- ai := lookupHandle(handle).(*aggInfo)
- ai.Done(ctx)
-}
-
-//export compareTrampoline
-func compareTrampoline(handlePtr uintptr, la C.int, a *C.char, lb C.int, b *C.char) C.int {
- cmp := lookupHandle(handlePtr).(func(string, string) int)
- return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb)))
-}
-
-//export commitHookTrampoline
-func commitHookTrampoline(handle uintptr) int {
- callback := lookupHandle(handle).(func() int)
- return callback()
-}
-
-//export rollbackHookTrampoline
-func rollbackHookTrampoline(handle uintptr) {
- callback := lookupHandle(handle).(func())
- callback()
-}
-
-//export updateHookTrampoline
-func updateHookTrampoline(handle uintptr, op int, db *C.char, table *C.char, rowid int64) {
- callback := lookupHandle(handle).(func(int, string, string, int64))
- callback(op, C.GoString(db), C.GoString(table), rowid)
-}
-
-//export authorizerTrampoline
-func authorizerTrampoline(handle uintptr, op int, arg1 *C.char, arg2 *C.char, arg3 *C.char) int {
- callback := lookupHandle(handle).(func(int, string, string, string) int)
- return callback(op, C.GoString(arg1), C.GoString(arg2), C.GoString(arg3))
-}
-
-// Use handles to avoid passing Go pointers to C.
-
-type handleVal struct {
- db *SQLiteConn
- val interface{}
-}
-
-var handleLock sync.Mutex
-var handleVals = make(map[uintptr]handleVal)
-var handleIndex uintptr = 100
-
-func newHandle(db *SQLiteConn, v interface{}) uintptr {
- handleLock.Lock()
- defer handleLock.Unlock()
- i := handleIndex
- handleIndex++
- handleVals[i] = handleVal{db, v}
- return i
-}
-
-func lookupHandle(handle uintptr) interface{} {
- handleLock.Lock()
- defer handleLock.Unlock()
- r, ok := handleVals[handle]
- if !ok {
- if handle >= 100 && handle < handleIndex {
- panic("deleted handle")
- } else {
- panic("invalid handle")
- }
- }
- return r.val
-}
-
-func deleteHandles(db *SQLiteConn) {
- handleLock.Lock()
- defer handleLock.Unlock()
- for handle, val := range handleVals {
- if val.db == db {
- delete(handleVals, handle)
- }
- }
-}
-
-// This is only here so that tests can refer to it.
-type callbackArgRaw C.sqlite3_value
-
-type callbackArgConverter func(*C.sqlite3_value) (reflect.Value, error)
-
-type callbackArgCast struct {
- f callbackArgConverter
- typ reflect.Type
-}
-
-func (c callbackArgCast) Run(v *C.sqlite3_value) (reflect.Value, error) {
- val, err := c.f(v)
- if err != nil {
- return reflect.Value{}, err
- }
- if !val.Type().ConvertibleTo(c.typ) {
- return reflect.Value{}, fmt.Errorf("cannot convert %s to %s", val.Type(), c.typ)
- }
- return val.Convert(c.typ), nil
-}
-
-func callbackArgInt64(v *C.sqlite3_value) (reflect.Value, error) {
- if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
- return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
- }
- return reflect.ValueOf(int64(C.sqlite3_value_int64(v))), nil
-}
-
-func callbackArgBool(v *C.sqlite3_value) (reflect.Value, error) {
- if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
- return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
- }
- i := int64(C.sqlite3_value_int64(v))
- val := false
- if i != 0 {
- val = true
- }
- return reflect.ValueOf(val), nil
-}
-
-func callbackArgFloat64(v *C.sqlite3_value) (reflect.Value, error) {
- if C.sqlite3_value_type(v) != C.SQLITE_FLOAT {
- return reflect.Value{}, fmt.Errorf("argument must be a FLOAT")
- }
- return reflect.ValueOf(float64(C.sqlite3_value_double(v))), nil
-}
-
-func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) {
- switch C.sqlite3_value_type(v) {
- case C.SQLITE_BLOB:
- l := C.sqlite3_value_bytes(v)
- p := C.sqlite3_value_blob(v)
- return reflect.ValueOf(C.GoBytes(p, l)), nil
- case C.SQLITE_TEXT:
- l := C.sqlite3_value_bytes(v)
- c := unsafe.Pointer(C.sqlite3_value_text(v))
- return reflect.ValueOf(C.GoBytes(c, l)), nil
- default:
- return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
- }
-}
-
-func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) {
- switch C.sqlite3_value_type(v) {
- case C.SQLITE_BLOB:
- l := C.sqlite3_value_bytes(v)
- p := (*C.char)(C.sqlite3_value_blob(v))
- return reflect.ValueOf(C.GoStringN(p, l)), nil
- case C.SQLITE_TEXT:
- c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v)))
- return reflect.ValueOf(C.GoString(c)), nil
- default:
- return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
- }
-}
-
-func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) {
- switch C.sqlite3_value_type(v) {
- case C.SQLITE_INTEGER:
- return callbackArgInt64(v)
- case C.SQLITE_FLOAT:
- return callbackArgFloat64(v)
- case C.SQLITE_TEXT:
- return callbackArgString(v)
- case C.SQLITE_BLOB:
- return callbackArgBytes(v)
- case C.SQLITE_NULL:
- // Interpret NULL as a nil byte slice.
- var ret []byte
- return reflect.ValueOf(ret), nil
- default:
- panic("unreachable")
- }
-}
-
-func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
- switch typ.Kind() {
- case reflect.Interface:
- if typ.NumMethod() != 0 {
- return nil, errors.New("the only supported interface type is interface{}")
- }
- return callbackArgGeneric, nil
- case reflect.Slice:
- if typ.Elem().Kind() != reflect.Uint8 {
- return nil, errors.New("the only supported slice type is []byte")
- }
- return callbackArgBytes, nil
- case reflect.String:
- return callbackArgString, nil
- case reflect.Bool:
- return callbackArgBool, nil
- case reflect.Int64:
- return callbackArgInt64, nil
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
- c := callbackArgCast{callbackArgInt64, typ}
- return c.Run, nil
- case reflect.Float64:
- return callbackArgFloat64, nil
- case reflect.Float32:
- c := callbackArgCast{callbackArgFloat64, typ}
- return c.Run, nil
- default:
- return nil, fmt.Errorf("don't know how to convert to %s", typ)
- }
-}
-
-func callbackConvertArgs(argv []*C.sqlite3_value, converters []callbackArgConverter, variadic callbackArgConverter) ([]reflect.Value, error) {
- var args []reflect.Value
-
- if len(argv) < len(converters) {
- return nil, fmt.Errorf("function requires at least %d arguments", len(converters))
- }
-
- for i, arg := range argv[:len(converters)] {
- v, err := converters[i](arg)
- if err != nil {
- return nil, err
- }
- args = append(args, v)
- }
-
- if variadic != nil {
- for _, arg := range argv[len(converters):] {
- v, err := variadic(arg)
- if err != nil {
- return nil, err
- }
- args = append(args, v)
- }
- }
- return args, nil
-}
-
-type callbackRetConverter func(*C.sqlite3_context, reflect.Value) error
-
-func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
- switch v.Type().Kind() {
- case reflect.Int64:
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
- v = v.Convert(reflect.TypeOf(int64(0)))
- case reflect.Bool:
- b := v.Interface().(bool)
- if b {
- v = reflect.ValueOf(int64(1))
- } else {
- v = reflect.ValueOf(int64(0))
- }
- default:
- return fmt.Errorf("cannot convert %s to INTEGER", v.Type())
- }
-
- C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Interface().(int64)))
- return nil
-}
-
-func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error {
- switch v.Type().Kind() {
- case reflect.Float64:
- case reflect.Float32:
- v = v.Convert(reflect.TypeOf(float64(0)))
- default:
- return fmt.Errorf("cannot convert %s to FLOAT", v.Type())
- }
-
- C.sqlite3_result_double(ctx, C.double(v.Interface().(float64)))
- return nil
-}
-
-func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error {
- if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 {
- return fmt.Errorf("cannot convert %s to BLOB", v.Type())
- }
- i := v.Interface()
- if i == nil || len(i.([]byte)) == 0 {
- C.sqlite3_result_null(ctx)
- } else {
- bs := i.([]byte)
- C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs)))
- }
- return nil
-}
-
-func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error {
- if v.Type().Kind() != reflect.String {
- return fmt.Errorf("cannot convert %s to TEXT", v.Type())
- }
- C._sqlite3_result_text(ctx, C.CString(v.Interface().(string)))
- return nil
-}
-
-func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error {
- return nil
-}
-
-func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
- switch typ.Kind() {
- case reflect.Interface:
- errorInterface := reflect.TypeOf((*error)(nil)).Elem()
- if typ.Implements(errorInterface) {
- return callbackRetNil, nil
- }
- fallthrough
- case reflect.Slice:
- if typ.Elem().Kind() != reflect.Uint8 {
- return nil, errors.New("the only supported slice type is []byte")
- }
- return callbackRetBlob, nil
- case reflect.String:
- return callbackRetText, nil
- case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
- return callbackRetInteger, nil
- case reflect.Float32, reflect.Float64:
- return callbackRetFloat, nil
- default:
- return nil, fmt.Errorf("don't know how to convert to %s", typ)
- }
-}
-
-func callbackError(ctx *C.sqlite3_context, err error) {
- cstr := C.CString(err.Error())
- defer C.free(unsafe.Pointer(cstr))
- C.sqlite3_result_error(ctx, cstr, C.int(-1))
-}
-
-// Test support code. Tests are not allowed to import "C", so we can't
-// declare any functions that use C.sqlite3_value.
-func callbackSyntheticForTests(v reflect.Value, err error) callbackArgConverter {
- return func(*C.sqlite3_value) (reflect.Value, error) {
- return v, err
- }
-}
diff --git a/vendor/github.com/mattn/go-sqlite3/doc.go b/vendor/github.com/mattn/go-sqlite3/doc.go
deleted file mode 100644
index c721f77..0000000
--- a/vendor/github.com/mattn/go-sqlite3/doc.go
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
-Package sqlite3 provides interface to SQLite3 databases.
-
-This works as a driver for database/sql.
-
-Installation
-
- go get github.com/mattn/go-sqlite3
-
-Supported Types
-
-Currently, go-sqlite3 supports the following data types.
-
- +------------------------------+
- |go | sqlite3 |
- |----------|-------------------|
- |nil | null |
- |int | integer |
- |int64 | integer |
- |float64 | float |
- |bool | integer |
- |[]byte | blob |
- |string | text |
- |time.Time | timestamp/datetime|
- +------------------------------+
-
-SQLite3 Extension
-
-You can write your own extension module for sqlite3. For example, below is an
-extension for a Regexp matcher operation.
-
- #include
- #include
- #include
- #include
-
- SQLITE_EXTENSION_INIT1
- static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) {
- if (argc >= 2) {
- const char *target = (const char *)sqlite3_value_text(argv[1]);
- const char *pattern = (const char *)sqlite3_value_text(argv[0]);
- const char* errstr = NULL;
- int erroff = 0;
- int vec[500];
- int n, rc;
- pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL);
- rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500);
- if (rc <= 0) {
- sqlite3_result_error(context, errstr, 0);
- return;
- }
- sqlite3_result_int(context, 1);
- }
- }
-
- #ifdef _WIN32
- __declspec(dllexport)
- #endif
- int sqlite3_extension_init(sqlite3 *db, char **errmsg,
- const sqlite3_api_routines *api) {
- SQLITE_EXTENSION_INIT2(api);
- return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8,
- (void*)db, regexp_func, NULL, NULL);
- }
-
-It needs to be built as a so/dll shared library. And you need to register
-the extension module like below.
-
- sql.Register("sqlite3_with_extensions",
- &sqlite3.SQLiteDriver{
- Extensions: []string{
- "sqlite3_mod_regexp",
- },
- })
-
-Then, you can use this extension.
-
- rows, err := db.Query("select text from mytable where name regexp '^golang'")
-
-Connection Hook
-
-You can hook and inject your code when the connection is established. database/sql
-doesn't provide a way to get native go-sqlite3 interfaces. So if you want,
-you need to set ConnectHook and get the SQLiteConn.
-
- sql.Register("sqlite3_with_hook_example",
- &sqlite3.SQLiteDriver{
- ConnectHook: func(conn *sqlite3.SQLiteConn) error {
- sqlite3conn = append(sqlite3conn, conn)
- return nil
- },
- })
-
-Go SQlite3 Extensions
-
-If you want to register Go functions as SQLite extension functions,
-call RegisterFunction from ConnectHook.
-
- regex = func(re, s string) (bool, error) {
- return regexp.MatchString(re, s)
- }
- sql.Register("sqlite3_with_go_func",
- &sqlite3.SQLiteDriver{
- ConnectHook: func(conn *sqlite3.SQLiteConn) error {
- return conn.RegisterFunc("regexp", regex, true)
- },
- })
-
-See the documentation of RegisterFunc for more details.
-
-*/
-package sqlite3
diff --git a/vendor/github.com/mattn/go-sqlite3/error.go b/vendor/github.com/mattn/go-sqlite3/error.go
deleted file mode 100644
index 49ab890..0000000
--- a/vendor/github.com/mattn/go-sqlite3/error.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright (C) 2014 Yasuhiro Matsumoto .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package sqlite3
-
-import "C"
-
-// ErrNo inherit errno.
-type ErrNo int
-
-// ErrNoMask is mask code.
-const ErrNoMask C.int = 0xff
-
-// ErrNoExtended is extended errno.
-type ErrNoExtended int
-
-// Error implement sqlite error code.
-type Error struct {
- Code ErrNo /* The error code returned by SQLite */
- ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */
- err string /* The error string returned by sqlite3_errmsg(),
- this usually contains more specific details. */
-}
-
-// result codes from http://www.sqlite.org/c3ref/c_abort.html
-var (
- ErrError = ErrNo(1) /* SQL error or missing database */
- ErrInternal = ErrNo(2) /* Internal logic error in SQLite */
- ErrPerm = ErrNo(3) /* Access permission denied */
- ErrAbort = ErrNo(4) /* Callback routine requested an abort */
- ErrBusy = ErrNo(5) /* The database file is locked */
- ErrLocked = ErrNo(6) /* A table in the database is locked */
- ErrNomem = ErrNo(7) /* A malloc() failed */
- ErrReadonly = ErrNo(8) /* Attempt to write a readonly database */
- ErrInterrupt = ErrNo(9) /* Operation terminated by sqlite3_interrupt() */
- ErrIoErr = ErrNo(10) /* Some kind of disk I/O error occurred */
- ErrCorrupt = ErrNo(11) /* The database disk image is malformed */
- ErrNotFound = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */
- ErrFull = ErrNo(13) /* Insertion failed because database is full */
- ErrCantOpen = ErrNo(14) /* Unable to open the database file */
- ErrProtocol = ErrNo(15) /* Database lock protocol error */
- ErrEmpty = ErrNo(16) /* Database is empty */
- ErrSchema = ErrNo(17) /* The database schema changed */
- ErrTooBig = ErrNo(18) /* String or BLOB exceeds size limit */
- ErrConstraint = ErrNo(19) /* Abort due to constraint violation */
- ErrMismatch = ErrNo(20) /* Data type mismatch */
- ErrMisuse = ErrNo(21) /* Library used incorrectly */
- ErrNoLFS = ErrNo(22) /* Uses OS features not supported on host */
- ErrAuth = ErrNo(23) /* Authorization denied */
- ErrFormat = ErrNo(24) /* Auxiliary database format error */
- ErrRange = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */
- ErrNotADB = ErrNo(26) /* File opened that is not a database file */
- ErrNotice = ErrNo(27) /* Notifications from sqlite3_log() */
- ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */
-)
-
-// Error return error message from errno.
-func (err ErrNo) Error() string {
- return Error{Code: err}.Error()
-}
-
-// Extend return extended errno.
-func (err ErrNo) Extend(by int) ErrNoExtended {
- return ErrNoExtended(int(err) | (by << 8))
-}
-
-// Error return error message that is extended code.
-func (err ErrNoExtended) Error() string {
- return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error()
-}
-
-func (err Error) Error() string {
- if err.err != "" {
- return err.err
- }
- return errorString(err)
-}
-
-// result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html
-var (
- ErrIoErrRead = ErrIoErr.Extend(1)
- ErrIoErrShortRead = ErrIoErr.Extend(2)
- ErrIoErrWrite = ErrIoErr.Extend(3)
- ErrIoErrFsync = ErrIoErr.Extend(4)
- ErrIoErrDirFsync = ErrIoErr.Extend(5)
- ErrIoErrTruncate = ErrIoErr.Extend(6)
- ErrIoErrFstat = ErrIoErr.Extend(7)
- ErrIoErrUnlock = ErrIoErr.Extend(8)
- ErrIoErrRDlock = ErrIoErr.Extend(9)
- ErrIoErrDelete = ErrIoErr.Extend(10)
- ErrIoErrBlocked = ErrIoErr.Extend(11)
- ErrIoErrNoMem = ErrIoErr.Extend(12)
- ErrIoErrAccess = ErrIoErr.Extend(13)
- ErrIoErrCheckReservedLock = ErrIoErr.Extend(14)
- ErrIoErrLock = ErrIoErr.Extend(15)
- ErrIoErrClose = ErrIoErr.Extend(16)
- ErrIoErrDirClose = ErrIoErr.Extend(17)
- ErrIoErrSHMOpen = ErrIoErr.Extend(18)
- ErrIoErrSHMSize = ErrIoErr.Extend(19)
- ErrIoErrSHMLock = ErrIoErr.Extend(20)
- ErrIoErrSHMMap = ErrIoErr.Extend(21)
- ErrIoErrSeek = ErrIoErr.Extend(22)
- ErrIoErrDeleteNoent = ErrIoErr.Extend(23)
- ErrIoErrMMap = ErrIoErr.Extend(24)
- ErrIoErrGetTempPath = ErrIoErr.Extend(25)
- ErrIoErrConvPath = ErrIoErr.Extend(26)
- ErrLockedSharedCache = ErrLocked.Extend(1)
- ErrBusyRecovery = ErrBusy.Extend(1)
- ErrBusySnapshot = ErrBusy.Extend(2)
- ErrCantOpenNoTempDir = ErrCantOpen.Extend(1)
- ErrCantOpenIsDir = ErrCantOpen.Extend(2)
- ErrCantOpenFullPath = ErrCantOpen.Extend(3)
- ErrCantOpenConvPath = ErrCantOpen.Extend(4)
- ErrCorruptVTab = ErrCorrupt.Extend(1)
- ErrReadonlyRecovery = ErrReadonly.Extend(1)
- ErrReadonlyCantLock = ErrReadonly.Extend(2)
- ErrReadonlyRollback = ErrReadonly.Extend(3)
- ErrReadonlyDbMoved = ErrReadonly.Extend(4)
- ErrAbortRollback = ErrAbort.Extend(2)
- ErrConstraintCheck = ErrConstraint.Extend(1)
- ErrConstraintCommitHook = ErrConstraint.Extend(2)
- ErrConstraintForeignKey = ErrConstraint.Extend(3)
- ErrConstraintFunction = ErrConstraint.Extend(4)
- ErrConstraintNotNull = ErrConstraint.Extend(5)
- ErrConstraintPrimaryKey = ErrConstraint.Extend(6)
- ErrConstraintTrigger = ErrConstraint.Extend(7)
- ErrConstraintUnique = ErrConstraint.Extend(8)
- ErrConstraintVTab = ErrConstraint.Extend(9)
- ErrConstraintRowID = ErrConstraint.Extend(10)
- ErrNoticeRecoverWAL = ErrNotice.Extend(1)
- ErrNoticeRecoverRollback = ErrNotice.Extend(2)
- ErrWarningAutoIndex = ErrWarning.Extend(1)
-)
diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c
deleted file mode 100644
index 140d096..0000000
--- a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c
+++ /dev/null
@@ -1,224147 +0,0 @@
-#ifndef USE_LIBSQLITE3
-/******************************************************************************
-** This file is an amalgamation of many separate C source files from SQLite
-** version 3.29.0. By combining all the individual C code files into this
-** single large file, the entire code can be compiled as a single translation
-** unit. This allows many compilers to do optimizations that would not be
-** possible if the files were compiled separately. Performance improvements
-** of 5% or more are commonly seen when SQLite is compiled as a single
-** translation unit.
-**
-** This file is all you need to compile SQLite. To use SQLite in other
-** programs, you need this file and the "sqlite3.h" header file that defines
-** the programming interface to the SQLite library. (If you do not have
-** the "sqlite3.h" header file at hand, you will find a copy embedded within
-** the text of this file. Search for "Begin file sqlite3.h" to find the start
-** of the embedded sqlite3.h header file.) Additional code files may be needed
-** if you want a wrapper to interface SQLite with your choice of programming
-** language. The code for the "sqlite3" command-line shell is also in a
-** separate file. This file contains only code for the core SQLite library.
-*/
-#define SQLITE_CORE 1
-#define SQLITE_AMALGAMATION 1
-#ifndef SQLITE_PRIVATE
-# define SQLITE_PRIVATE static
-#endif
-/************** Begin file ctime.c *******************************************/
-/*
-** 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.
-*/
-
-#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
-
-/*
-** Include the configuration header output by 'configure' if we're using the
-** autoconf-based build
-*/
-#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
-#include "config.h"
-#define SQLITECONFIG_H 1
-#endif
-
-/* 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)
-
-/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
-** option requires a separate macro because legal values contain a single
-** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
-#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
-#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
-
-/*
-** 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 const char * const sqlite3azCompileOpt[] = {
-
-/*
-** BEGIN CODE GENERATED BY tool/mkctime.tcl
-*/
-#if SQLITE_32BIT_ROWID
- "32BIT_ROWID",
-#endif
-#if SQLITE_4_BYTE_ALIGNED_MALLOC
- "4_BYTE_ALIGNED_MALLOC",
-#endif
-#if SQLITE_64BIT_STATS
- "64BIT_STATS",
-#endif
-#if SQLITE_ALLOW_COVERING_INDEX_SCAN
- "ALLOW_COVERING_INDEX_SCAN",
-#endif
-#if SQLITE_ALLOW_URI_AUTHORITY
- "ALLOW_URI_AUTHORITY",
-#endif
-#ifdef SQLITE_BITMASK_TYPE
- "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
-#endif
-#if SQLITE_BUG_COMPATIBLE_20160819
- "BUG_COMPATIBLE_20160819",
-#endif
-#if SQLITE_CASE_SENSITIVE_LIKE
- "CASE_SENSITIVE_LIKE",
-#endif
-#if SQLITE_CHECK_PAGES
- "CHECK_PAGES",
-#endif
-#if defined(__clang__) && defined(__clang_major__)
- "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
- CTIMEOPT_VAL(__clang_minor__) "."
- CTIMEOPT_VAL(__clang_patchlevel__),
-#elif defined(_MSC_VER)
- "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
-#elif defined(__GNUC__) && defined(__VERSION__)
- "COMPILER=gcc-" __VERSION__,
-#endif
-#if SQLITE_COVERAGE_TEST
- "COVERAGE_TEST",
-#endif
-#if SQLITE_DEBUG
- "DEBUG",
-#endif
-#if SQLITE_DEFAULT_AUTOMATIC_INDEX
- "DEFAULT_AUTOMATIC_INDEX",
-#endif
-#if SQLITE_DEFAULT_AUTOVACUUM
- "DEFAULT_AUTOVACUUM",
-#endif
-#ifdef SQLITE_DEFAULT_CACHE_SIZE
- "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
-#endif
-#if SQLITE_DEFAULT_CKPTFULLFSYNC
- "DEFAULT_CKPTFULLFSYNC",
-#endif
-#ifdef SQLITE_DEFAULT_FILE_FORMAT
- "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
-#endif
-#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
- "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
-#endif
-#if SQLITE_DEFAULT_FOREIGN_KEYS
- "DEFAULT_FOREIGN_KEYS",
-#endif
-#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
- "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
-#endif
-#ifdef SQLITE_DEFAULT_LOCKING_MODE
- "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
-#endif
-#ifdef SQLITE_DEFAULT_LOOKASIDE
- "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
-#endif
-#if SQLITE_DEFAULT_MEMSTATUS
- "DEFAULT_MEMSTATUS",
-#endif
-#ifdef SQLITE_DEFAULT_MMAP_SIZE
- "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_PAGE_SIZE
- "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
- "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
-#endif
-#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
- "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
-#endif
-#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
- "DEFAULT_RECURSIVE_TRIGGERS",
-#endif
-#ifdef SQLITE_DEFAULT_ROWEST
- "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
-#endif
-#ifdef SQLITE_DEFAULT_SECTOR_SIZE
- "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
-#endif
-#ifdef SQLITE_DEFAULT_SYNCHRONOUS
- "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
-#endif
-#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
- "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
-#endif
-#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
- "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
-#endif
-#ifdef SQLITE_DEFAULT_WORKER_THREADS
- "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
-#endif
-#if SQLITE_DIRECT_OVERFLOW_READ
- "DIRECT_OVERFLOW_READ",
-#endif
-#if SQLITE_DISABLE_DIRSYNC
- "DISABLE_DIRSYNC",
-#endif
-#if SQLITE_DISABLE_FTS3_UNICODE
- "DISABLE_FTS3_UNICODE",
-#endif
-#if SQLITE_DISABLE_FTS4_DEFERRED
- "DISABLE_FTS4_DEFERRED",
-#endif
-#if SQLITE_DISABLE_INTRINSIC
- "DISABLE_INTRINSIC",
-#endif
-#if SQLITE_DISABLE_LFS
- "DISABLE_LFS",
-#endif
-#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
- "DISABLE_PAGECACHE_OVERFLOW_STATS",
-#endif
-#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
- "DISABLE_SKIPAHEAD_DISTINCT",
-#endif
-#ifdef SQLITE_ENABLE_8_3_NAMES
- "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
-#endif
-#if SQLITE_ENABLE_API_ARMOR
- "ENABLE_API_ARMOR",
-#endif
-#if SQLITE_ENABLE_ATOMIC_WRITE
- "ENABLE_ATOMIC_WRITE",
-#endif
-#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
- "ENABLE_BATCH_ATOMIC_WRITE",
-#endif
-#if SQLITE_ENABLE_CEROD
- "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
-#endif
-#if SQLITE_ENABLE_COLUMN_METADATA
- "ENABLE_COLUMN_METADATA",
-#endif
-#if SQLITE_ENABLE_COLUMN_USED_MASK
- "ENABLE_COLUMN_USED_MASK",
-#endif
-#if SQLITE_ENABLE_COSTMULT
- "ENABLE_COSTMULT",
-#endif
-#if SQLITE_ENABLE_CURSOR_HINTS
- "ENABLE_CURSOR_HINTS",
-#endif
-#if SQLITE_ENABLE_DBSTAT_VTAB
- "ENABLE_DBSTAT_VTAB",
-#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_FTS3_TOKENIZER
- "ENABLE_FTS3_TOKENIZER",
-#endif
-#if SQLITE_ENABLE_FTS4
- "ENABLE_FTS4",
-#endif
-#if SQLITE_ENABLE_FTS5
- "ENABLE_FTS5",
-#endif
-#if SQLITE_ENABLE_GEOPOLY
- "ENABLE_GEOPOLY",
-#endif
-#if SQLITE_ENABLE_HIDDEN_COLUMNS
- "ENABLE_HIDDEN_COLUMNS",
-#endif
-#if SQLITE_ENABLE_ICU
- "ENABLE_ICU",
-#endif
-#if SQLITE_ENABLE_IOTRACE
- "ENABLE_IOTRACE",
-#endif
-#if SQLITE_ENABLE_JSON1
- "ENABLE_JSON1",
-#endif
-#if SQLITE_ENABLE_LOAD_EXTENSION
- "ENABLE_LOAD_EXTENSION",
-#endif
-#ifdef 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_MULTIPLEX
- "ENABLE_MULTIPLEX",
-#endif
-#if SQLITE_ENABLE_NORMALIZE
- "ENABLE_NORMALIZE",
-#endif
-#if SQLITE_ENABLE_NULL_TRIM
- "ENABLE_NULL_TRIM",
-#endif
-#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
- "ENABLE_OVERSIZE_CELL_CHECK",
-#endif
-#if SQLITE_ENABLE_PREUPDATE_HOOK
- "ENABLE_PREUPDATE_HOOK",
-#endif
-#if SQLITE_ENABLE_QPSG
- "ENABLE_QPSG",
-#endif
-#if SQLITE_ENABLE_RBU
- "ENABLE_RBU",
-#endif
-#if SQLITE_ENABLE_RTREE
- "ENABLE_RTREE",
-#endif
-#if SQLITE_ENABLE_SELECTTRACE
- "ENABLE_SELECTTRACE",
-#endif
-#if SQLITE_ENABLE_SESSION
- "ENABLE_SESSION",
-#endif
-#if SQLITE_ENABLE_SNAPSHOT
- "ENABLE_SNAPSHOT",
-#endif
-#if SQLITE_ENABLE_SORTER_REFERENCES
- "ENABLE_SORTER_REFERENCES",
-#endif
-#if SQLITE_ENABLE_SQLLOG
- "ENABLE_SQLLOG",
-#endif
-#if defined(SQLITE_ENABLE_STAT4)
- "ENABLE_STAT4",
-#elif defined(SQLITE_ENABLE_STAT3)
- "ENABLE_STAT3",
-#endif
-#if SQLITE_ENABLE_STMTVTAB
- "ENABLE_STMTVTAB",
-#endif
-#if SQLITE_ENABLE_STMT_SCANSTATUS
- "ENABLE_STMT_SCANSTATUS",
-#endif
-#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
- "ENABLE_UNKNOWN_SQL_FUNCTION",
-#endif
-#if SQLITE_ENABLE_UNLOCK_NOTIFY
- "ENABLE_UNLOCK_NOTIFY",
-#endif
-#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
- "ENABLE_UPDATE_DELETE_LIMIT",
-#endif
-#if SQLITE_ENABLE_URI_00_ERROR
- "ENABLE_URI_00_ERROR",
-#endif
-#if SQLITE_ENABLE_VFSTRACE
- "ENABLE_VFSTRACE",
-#endif
-#if SQLITE_ENABLE_WHERETRACE
- "ENABLE_WHERETRACE",
-#endif
-#if SQLITE_ENABLE_ZIPVFS
- "ENABLE_ZIPVFS",
-#endif
-#if SQLITE_EXPLAIN_ESTIMATED_ROWS
- "EXPLAIN_ESTIMATED_ROWS",
-#endif
-#if SQLITE_EXTRA_IFNULLROW
- "EXTRA_IFNULLROW",
-#endif
-#ifdef SQLITE_EXTRA_INIT
- "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
-#endif
-#ifdef SQLITE_EXTRA_SHUTDOWN
- "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
-#endif
-#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
- "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
-#endif
-#if SQLITE_FTS5_ENABLE_TEST_MI
- "FTS5_ENABLE_TEST_MI",
-#endif
-#if SQLITE_FTS5_NO_WITHOUT_ROWID
- "FTS5_NO_WITHOUT_ROWID",
-#endif
-#if SQLITE_HAS_CODEC
- "HAS_CODEC",
-#endif
-#if HAVE_ISNAN || 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_INLINE_MEMCPY
- "INLINE_MEMCPY",
-#endif
-#if SQLITE_INT64_TYPE
- "INT64_TYPE",
-#endif
-#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
- "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
-#endif
-#if SQLITE_LIKE_DOESNT_MATCH_BLOBS
- "LIKE_DOESNT_MATCH_BLOBS",
-#endif
-#if SQLITE_LOCK_TRACE
- "LOCK_TRACE",
-#endif
-#if SQLITE_LOG_CACHE_SPILL
- "LOG_CACHE_SPILL",
-#endif
-#ifdef SQLITE_MALLOC_SOFT_LIMIT
- "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
-#endif
-#ifdef SQLITE_MAX_ATTACHED
- "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
-#endif
-#ifdef SQLITE_MAX_COLUMN
- "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
-#endif
-#ifdef SQLITE_MAX_COMPOUND_SELECT
- "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
-#endif
-#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
- "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
-#endif
-#ifdef SQLITE_MAX_EXPR_DEPTH
- "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
-#endif
-#ifdef SQLITE_MAX_FUNCTION_ARG
- "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
-#endif
-#ifdef SQLITE_MAX_LENGTH
- "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
-#endif
-#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
- "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
-#endif
-#ifdef SQLITE_MAX_MEMORY
- "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
-#endif
-#ifdef SQLITE_MAX_MMAP_SIZE
- "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
-#endif
-#ifdef SQLITE_MAX_MMAP_SIZE_
- "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
-#endif
-#ifdef SQLITE_MAX_PAGE_COUNT
- "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
-#endif
-#ifdef SQLITE_MAX_PAGE_SIZE
- "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
-#endif
-#ifdef SQLITE_MAX_SCHEMA_RETRY
- "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
-#endif
-#ifdef SQLITE_MAX_SQL_LENGTH
- "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
-#endif
-#ifdef SQLITE_MAX_TRIGGER_DEPTH
- "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
-#endif
-#ifdef SQLITE_MAX_VARIABLE_NUMBER
- "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
-#endif
-#ifdef SQLITE_MAX_VDBE_OP
- "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
-#endif
-#ifdef SQLITE_MAX_WORKER_THREADS
- "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
-#endif
-#if SQLITE_MEMDEBUG
- "MEMDEBUG",
-#endif
-#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
- "MIXED_ENDIAN_64BIT_FLOAT",
-#endif
-#if SQLITE_MMAP_READWRITE
- "MMAP_READWRITE",
-#endif
-#if SQLITE_MUTEX_NOOP
- "MUTEX_NOOP",
-#endif
-#if SQLITE_MUTEX_NREF
- "MUTEX_NREF",
-#endif
-#if SQLITE_MUTEX_OMIT
- "MUTEX_OMIT",
-#endif
-#if SQLITE_MUTEX_PTHREADS
- "MUTEX_PTHREADS",
-#endif
-#if SQLITE_MUTEX_W32
- "MUTEX_W32",
-#endif
-#if SQLITE_NEED_ERR_NAME
- "NEED_ERR_NAME",
-#endif
-#if SQLITE_NOINLINE
- "NOINLINE",
-#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 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_CAST
- "OMIT_CAST",
-#endif
-#if SQLITE_OMIT_CHECK
- "OMIT_CHECK",
-#endif
-#if SQLITE_OMIT_COMPLETE
- "OMIT_COMPLETE",
-#endif
-#if SQLITE_OMIT_COMPOUND_SELECT
- "OMIT_COMPOUND_SELECT",
-#endif
-#if SQLITE_OMIT_CONFLICT_CLAUSE
- "OMIT_CONFLICT_CLAUSE",
-#endif
-#if SQLITE_OMIT_CTE
- "OMIT_CTE",
-#endif
-#if SQLITE_OMIT_DATETIME_FUNCS
- "OMIT_DATETIME_FUNCS",
-#endif
-#if SQLITE_OMIT_DECLTYPE
- "OMIT_DECLTYPE",
-#endif
-#if 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 SQLITE_OMIT_GET_TABLE
- "OMIT_GET_TABLE",
-#endif
-#if SQLITE_OMIT_HEX_INTEGER
- "OMIT_HEX_INTEGER",
-#endif
-#if 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 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_PARSER_TRACE
- "OMIT_PARSER_TRACE",
-#endif
-#if SQLITE_OMIT_POPEN
- "OMIT_POPEN",
-#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 SQLITE_OMIT_SHARED_CACHE
- "OMIT_SHARED_CACHE",
-#endif
-#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
- "OMIT_SHUTDOWN_DIRECTORIES",
-#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_TEST_CONTROL
- "OMIT_TEST_CONTROL",
-#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 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_PCACHE_SEPARATE_HEADER
- "PCACHE_SEPARATE_HEADER",
-#endif
-#if SQLITE_PERFORMANCE_TRACE
- "PERFORMANCE_TRACE",
-#endif
-#if SQLITE_POWERSAFE_OVERWRITE
- "POWERSAFE_OVERWRITE",
-#endif
-#if SQLITE_PREFER_PROXY_LOCKING
- "PREFER_PROXY_LOCKING",
-#endif
-#if SQLITE_PROXY_DEBUG
- "PROXY_DEBUG",
-#endif
-#if SQLITE_REVERSE_UNORDERED_SELECTS
- "REVERSE_UNORDERED_SELECTS",
-#endif
-#if SQLITE_RTREE_INT_ONLY
- "RTREE_INT_ONLY",
-#endif
-#if SQLITE_SECURE_DELETE
- "SECURE_DELETE",
-#endif
-#if SQLITE_SMALL_STACK
- "SMALL_STACK",
-#endif
-#ifdef SQLITE_SORTER_PMASZ
- "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
-#endif
-#if SQLITE_SOUNDEX
- "SOUNDEX",
-#endif
-#ifdef SQLITE_STAT4_SAMPLES
- "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
-#endif
-#ifdef SQLITE_STMTJRNL_SPILL
- "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
-#endif
-#if SQLITE_SUBSTR_COMPATIBILITY
- "SUBSTR_COMPATIBILITY",
-#endif
-#if SQLITE_SYSTEM_MALLOC
- "SYSTEM_MALLOC",
-#endif
-#if SQLITE_TCL
- "TCL",
-#endif
-#ifdef SQLITE_TEMP_STORE
- "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
-#endif
-#if SQLITE_TEST
- "TEST",
-#endif
-#if defined(SQLITE_THREADSAFE)
- "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
-#elif defined(THREADSAFE)
- "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
-#else
- "THREADSAFE=1",
-#endif
-#if SQLITE_UNLINK_AFTER_CLOSE
- "UNLINK_AFTER_CLOSE",
-#endif
-#if SQLITE_UNTESTABLE
- "UNTESTABLE",
-#endif
-#if SQLITE_USER_AUTHENTICATION
- "USER_AUTHENTICATION",
-#endif
-#if SQLITE_USE_ALLOCA
- "USE_ALLOCA",
-#endif
-#if SQLITE_USE_FCNTL_TRACE
- "USE_FCNTL_TRACE",
-#endif
-#if SQLITE_USE_URI
- "USE_URI",
-#endif
-#if SQLITE_VDBE_COVERAGE
- "VDBE_COVERAGE",
-#endif
-#if SQLITE_WIN32_MALLOC
- "WIN32_MALLOC",
-#endif
-#if SQLITE_ZERO_MALLOC
- "ZERO_MALLOC",
-#endif
-/*
-** END CODE GENERATED BY tool/mkctime.tcl
-*/
-};
-
-SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
- *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
- return (const char**)sqlite3azCompileOpt;
-}
-
-#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
-
-/************** End of ctime.c ***********************************************/
-/************** Begin file sqliteInt.h ***************************************/
-/*
-** 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.
-**
-*/
-#ifndef SQLITEINT_H
-#define SQLITEINT_H
-
-/* Special Comments:
-**
-** Some comments have special meaning to the tools that measure test
-** coverage:
-**
-** NO_TEST - The branches on this line are not
-** measured by branch coverage. This is
-** used on lines of code that actually
-** implement parts of coverage testing.
-**
-** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
-** and the correct answer is still obtained,
-** though perhaps more slowly.
-**
-** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
-** and the correct answer is still obtained,
-** though perhaps more slowly.
-**
-** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
-** that would be harmless and undetectable
-** if it did occur.
-**
-** In all cases, the special comment must be enclosed in the usual
-** slash-asterisk...asterisk-slash comment marks, with no spaces between the
-** asterisks and the comment text.
-*/
-
-/*
-** Make sure the Tcl calling convention macro is defined. This macro is
-** only used by test code and Tcl integration code.
-*/
-#ifndef SQLITE_TCLAPI
-# define SQLITE_TCLAPI
-#endif
-
-/*
-** Include the header file used to customize the compiler options for MSVC.
-** This should be done first so that it can successfully prevent spurious
-** compiler warnings due to subsequent content in this file and other files
-** that are included by this file.
-*/
-/************** Include msvc.h in the middle of sqliteInt.h ******************/
-/************** Begin file msvc.h ********************************************/
-/*
-** 2015 January 12
-**
-** 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 MSVC.
-*/
-#ifndef SQLITE_MSVC_H
-#define SQLITE_MSVC_H
-
-#if defined(_MSC_VER)
-#pragma warning(disable : 4054)
-#pragma warning(disable : 4055)
-#pragma warning(disable : 4100)
-#pragma warning(disable : 4127)
-#pragma warning(disable : 4130)
-#pragma warning(disable : 4152)
-#pragma warning(disable : 4189)
-#pragma warning(disable : 4206)
-#pragma warning(disable : 4210)
-#pragma warning(disable : 4232)
-#pragma warning(disable : 4244)
-#pragma warning(disable : 4305)
-#pragma warning(disable : 4306)
-#pragma warning(disable : 4702)
-#pragma warning(disable : 4706)
-#endif /* defined(_MSC_VER) */
-
-#if defined(_MSC_VER) && !defined(_WIN64)
-#undef SQLITE_4_BYTE_ALIGNED_MALLOC
-#define SQLITE_4_BYTE_ALIGNED_MALLOC
-#endif /* defined(_MSC_VER) && !defined(_WIN64) */
-
-#endif /* SQLITE_MSVC_H */
-
-/************** End of msvc.h ************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/*
-** Special setup for VxWorks
-*/
-/************** Include vxworks.h in the middle of sqliteInt.h ***************/
-/************** Begin file vxworks.h *****************************************/
-/*
-** 2015-03-02
-**
-** 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 Wind River's VxWorks
-*/
-#if defined(__RTP__) || defined(_WRS_KERNEL)
-/* This is VxWorks. Set up things specially for that OS
-*/
-#include
-#include /* amalgamator: dontcache */
-#define OS_VXWORKS 1
-#define SQLITE_OS_OTHER 0
-#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
-#define SQLITE_OMIT_LOAD_EXTENSION 1
-#define SQLITE_ENABLE_LOCKING_STYLE 0
-#define HAVE_UTIME 1
-#else
-/* This is not VxWorks. */
-#define OS_VXWORKS 0
-#define HAVE_FCHOWN 1
-#define HAVE_READLINK 1
-#define HAVE_LSTAT 1
-#endif /* defined(_WRS_KERNEL) */
-
-/************** End of vxworks.h *********************************************/
-/************** Continuing where we left off in 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.
-**
-** The previous paragraph was written in 2005. (This paragraph is written
-** on 2008-11-28.) These days, all Linux kernels support large files, so
-** you should probably leave LFS enabled. But some embedded platforms might
-** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
-**
-** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
-*/
-#ifndef SQLITE_DISABLE_LFS
-# define _LARGE_FILE 1
-# ifndef _FILE_OFFSET_BITS
-# define _FILE_OFFSET_BITS 64
-# endif
-# define _LARGEFILE_SOURCE 1
-#endif
-
-/* The GCC_VERSION and MSVC_VERSION macros are used to
-** conditionally include optimizations for each of these compilers. A
-** value of 0 means that compiler is not being used. The
-** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
-** optimizations, and hence set all compiler macros to 0
-**
-** There was once also a CLANG_VERSION macro. However, we learn that the
-** version numbers in clang are for "marketing" only and are inconsistent
-** and unreliable. Fortunately, all versions of clang also recognize the
-** gcc version numbers and have reasonable settings for gcc version numbers,
-** so the GCC_VERSION macro will be set to a correct non-zero value even
-** when compiling with clang.
-*/
-#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
-# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
-#else
-# define GCC_VERSION 0
-#endif
-#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
-# define MSVC_VERSION _MSC_VER
-#else
-# define MSVC_VERSION 0
-#endif
-
-/* Needed for various definitions... */
-#if defined(__GNUC__) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
-#endif
-
-#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
-# define _BSD_SOURCE
-#endif
-
-/*
-** For MinGW, check to see if we can include the header file containing its
-** version information, among other things. Normally, this internal MinGW
-** header file would [only] be included automatically by other MinGW header
-** files; however, the contained version information is now required by this
-** header file to work around binary compatibility issues (see below) and
-** this is the only known way to reliably obtain it. This entire #if block
-** would be completely unnecessary if there was any other way of detecting
-** MinGW via their preprocessor (e.g. if they customized their GCC to define
-** some MinGW-specific macros). When compiling for MinGW, either the
-** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
-** defined; otherwise, detection of conditions specific to MinGW will be
-** disabled.
-*/
-#if defined(_HAVE_MINGW_H)
-# include "mingw.h"
-#elif defined(_HAVE__MINGW_H)
-# include "_mingw.h"
-#endif
-
-/*
-** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
-** define is required to maintain binary compatibility with the MSVC runtime
-** library in use (e.g. for Windows XP).
-*/
-#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
- defined(_WIN32) && !defined(_WIN64) && \
- defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
- defined(__MSVCRT__)
-# define _USE_32BIT_TIME_T
-#endif
-
-/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
-** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
-** MinGW.
-*/
-/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
-/************** Begin file sqlite3.h *****************************************/
-/*
-** 2001-09-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 supposed 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.
-*/
-#ifndef SQLITE3_H
-#define SQLITE3_H
-#include /* Needed for the definition of va_list */
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#if 0
-extern "C" {
-#endif
-
-
-/*
-** Provide the ability to override linkage features of the interface.
-*/
-#ifndef SQLITE_EXTERN
-# define SQLITE_EXTERN extern
-#endif
-#ifndef SQLITE_API
-# define SQLITE_API
-#endif
-#ifndef SQLITE_CDECL
-# define SQLITE_CDECL
-#endif
-#ifndef SQLITE_APICALL
-# define SQLITE_APICALL
-#endif
-#ifndef SQLITE_STDCALL
-# define SQLITE_STDCALL SQLITE_APICALL
-#endif
-#ifndef SQLITE_CALLBACK
-# define SQLITE_CALLBACK
-#endif
-#ifndef SQLITE_SYSAPI
-# define SQLITE_SYSAPI
-#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 supported for backwards
-** compatibility only. Application writers should be aware that
-** experimental interfaces are subject to change in point releases.
-**
-** These macros used to resolve to various kinds of compiler magic that
-** would generate warning messages when they were used. But that
-** compiler magic ended up generating such a flurry of bug reports
-** that we have taken it all out and gone back to using simple
-** noop macros.
-*/
-#define SQLITE_DEPRECATED
-#define SQLITE_EXPERIMENTAL
-
-/*
-** Ensure these symbols were not defined by some previous header file.
-*/
-#ifdef SQLITE_VERSION
-# undef SQLITE_VERSION
-#endif
-#ifdef SQLITE_VERSION_NUMBER
-# undef SQLITE_VERSION_NUMBER
-#endif
-
-/*
-** CAPI3REF: Compile-Time Library Version Numbers
-**
-** ^(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] ([dateof: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 a SHA1
-** or SHA3-256 hash of the entire source tree. If the source code has
-** been edited in any way since it was last checked in, then the last
-** four hexadecimal digits of the hash may be modified.
-**
-** See also: [sqlite3_libversion()],
-** [sqlite3_libversion_number()], [sqlite3_sourceid()],
-** [sqlite_version()] and [sqlite_source_id()].
-*/
-#define SQLITE_VERSION "3.29.0"
-#define SQLITE_VERSION_NUMBER 3029000
-#define SQLITE_SOURCE_ID "2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6"
-
-/*
-** 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 assert() statements in their application to
-** verify that values returned by these interfaces match the macros in
-** the header, and thus ensure that the application is
-** compiled with matching library and header files.
-**
-**
-** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
-** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
-** 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. Except if SQLite is built
-** using an edited copy of [the amalgamation], then the last four characters
-** of the hash might be different from [SQLITE_SOURCE_ID].)^
-**
-** See also: [sqlite_version()] and [sqlite_source_id()].
-*/
-SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
-SQLITE_API const char *sqlite3_libversion(void);
-SQLITE_API const char *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].
-*/
-#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
-SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
-SQLITE_API const char *sqlite3_compileoption_get(int N);
-#else
-# define sqlite3_compileoption_used(X) 0
-# define sqlite3_compileoption_get(X) ((void*)0)
-#endif
-
-/*
-** CAPI3REF: Test To See If The Library Is Threadsafe
-**
-** ^The sqlite3_threadsafe() function returns zero if and only if
-** SQLite was compiled with 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_SERIALIZED]. ^(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()]
-** and [sqlite3_close_v2()] are its destructors. 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.
-*/
-#ifdef SQLITE_INT64_TYPE
- typedef SQLITE_INT64_TYPE sqlite_int64;
-# ifdef SQLITE_UINT64_TYPE
- typedef SQLITE_UINT64_TYPE sqlite_uint64;
-# else
- typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
-# endif
-#elif defined(_MSC_VER) || defined(__BORLANDC__)
- typedef __int64 sqlite_int64;
- typedef unsigned __int64 sqlite_uint64;
-#else
- typedef long long int sqlite_int64;
- typedef unsigned long long int sqlite_uint64;
-#endif
-typedef sqlite_int64 sqlite3_int64;
-typedef sqlite_uint64 sqlite3_uint64;
-
-/*
-** If compiling for a processor that lacks floating point support,
-** substitute integer for floating-point.
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define double sqlite3_int64
-#endif
-
-/*
-** CAPI3REF: Closing A Database Connection
-** DESTRUCTOR: sqlite3
-**
-** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
-** for the [sqlite3] object.
-** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
-** the [sqlite3] object is successfully destroyed and all associated
-** resources are deallocated.
-**
-** ^If the database connection is associated with unfinalized prepared
-** statements or unfinished sqlite3_backup objects then sqlite3_close()
-** will leave the database connection open and return [SQLITE_BUSY].
-** ^If sqlite3_close_v2() is called with unfinalized prepared statements
-** and/or unfinished sqlite3_backups, then the database connection becomes
-** an unusable "zombie" which will automatically be deallocated when the
-** last prepared statement is finalized or the last sqlite3_backup is
-** finished. The sqlite3_close_v2() interface is intended for use with
-** host languages that are garbage collected, and where the order in which
-** destructors are called is arbitrary.
-**
-** Applications should [sqlite3_finalize | finalize] all [prepared statements],
-** [sqlite3_blob_close | close] all [BLOB handles], and
-** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
-** with the [sqlite3] object prior to attempting to close the object. ^If
-** sqlite3_close_v2() is called on a [database connection] that still has
-** outstanding [prepared statements], [BLOB handles], and/or
-** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
-** of resources is deferred until all [prepared statements], [BLOB handles],
-** and [sqlite3_backup] objects are also destroyed.
-**
-** ^If an [sqlite3] object is destroyed while a transaction is open,
-** the transaction is automatically rolled back.
-**
-** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(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() or sqlite3_close_v2() with a NULL pointer
-** argument is a harmless no-op.
-*/
-SQLITE_API int sqlite3_close(sqlite3*);
-SQLITE_API int sqlite3_close_v2(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
-** METHOD: sqlite3
-**
-** 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
-** 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 ensure that the 1st parameter to sqlite3_exec()
-** is a valid and open [database connection].
-**
- The application must not close the [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 */
- const char *sql, /* SQL to be evaluated */
- int (*callback)(void*,int,char**,char**), /* Callback function */
- void *, /* 1st argument to callback */
- char **errmsg /* Error msg written here */
-);
-
-/*
-** CAPI3REF: Result Codes
-** KEYWORDS: {result code definitions}
-**
-** Many SQLite functions return an integer result code from the set shown
-** here in order to indicate success or failure.
-**
-** New error codes may be added in future versions of SQLite.
-**
-** See also: [extended result code definitions]
-*/
-#define SQLITE_OK 0 /* Successful result */
-/* beginning-of-error-codes */
-#define SQLITE_ERROR 1 /* Generic error */
-#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 /* Internal use only */
-#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 /* Not used */
-#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_NOTICE 27 /* Notifications from sqlite3_log() */
-#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
-#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
-#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
-/* end-of-error-codes */
-
-/*
-** CAPI3REF: Extended Result Codes
-** KEYWORDS: {extended result code definitions}
-**
-** In its default configuration, SQLite API routines return one of 30 integer
-** [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 [dateof:3.3.8]
-** and later) include
-** support for additional result codes that provide more detailed information
-** about errors. These [extended result codes] are enabled or disabled
-** on a per database connection basis using the
-** [sqlite3_extended_result_codes()] API. Or, the extended code for
-** the most recent error can be obtained using
-** [sqlite3_extended_errcode()].
-*/
-#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
-#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
-#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
-#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_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
-#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
-#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
-#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
-#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
-#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
-#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
-#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
-#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
-#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
-#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
-#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
-#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
-#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
-#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
-#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
-#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
-#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
-#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
-#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
-#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
-#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
-#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
-#define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
-#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
-#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
-#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
-#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
-#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
-#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
-#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
-#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
-#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
-#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
-#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
-#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
-#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
-#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
-#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
-#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
-#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
-#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<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_MEMORY 0x00000080 /* 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 */
-
-/*
-** CAPI3REF: Device Characteristics
-**
-** The xDeviceCharacteristics method of the [sqlite3_io_methods]
-** object returns an integer which is a vector of 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(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
-** after reboot following a crash or power loss, the only bytes in a
-** file that were written at the application level might have changed
-** and that adjacent bytes, even bytes within the same sector are
-** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
-** flag indicates that a file cannot be deleted when open. The
-** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
-** read-only media and cannot be changed even by processes with
-** elevated privileges.
-**
-** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
-** filesystem supports doing multiple write operations atomically when those
-** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
-** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
-*/
-#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
-#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
-#define SQLITE_IOCAP_IMMUTABLE 0x00002000
-#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
-
-/*
-** 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
-
-/*
-** 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
-
-/*
-** 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 */
-};
-
-/*
-** 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 [file control opcodes | 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]
-**
- [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
-**
- [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
-**
- [SQLITE_IOCAP_IMMUTABLE]
-**
- [SQLITE_IOCAP_BATCH_ATOMIC]
-**
-**
-** The SQLITE_IOCAP_ATOMIC property means that all writes of
-** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
-** mean that writes of blocks that are nnn bytes in size and
-** are aligned to an address which is an integer multiple of
-** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
-** that when data is appended to a file, the data is appended
-** first then the size of the file is extended, never the other
-** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
-** information is written to disk in the same order as calls
-** to xWrite().
-**
-** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
-** in the unread portions of the buffer with zeros. A VFS that
-** fails to zero-fill short reads might seem to work. However,
-** failure to zero-fill short reads will eventually lead to
-** database corruption.
-*/
-typedef struct sqlite3_io_methods sqlite3_io_methods;
-struct sqlite3_io_methods {
- int iVersion;
- int (*xClose)(sqlite3_file*);
- int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
- int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
- int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
- int (*xSync)(sqlite3_file*, int flags);
- int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
- int (*xLock)(sqlite3_file*, int);
- int (*xUnlock)(sqlite3_file*, int);
- int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
- int (*xFileControl)(sqlite3_file*, int op, void *pArg);
- int (*xSectorSize)(sqlite3_file*);
- int (*xDeviceCharacteristics)(sqlite3_file*);
- /* Methods above are valid for version 1 */
- int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void 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 */
- int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
- int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
- /* Methods above are valid for version 3 */
- /* Additional methods may be added in future releases */
-};
-
-/*
-** CAPI3REF: Standard File Control Opcodes
-** KEYWORDS: {file control opcodes} {file control opcode}
-**
-** These integer constants are opcodes for the xFileControl method
-** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
-** interface.
-**
-**
-** - [[SQLITE_FCNTL_LOCKSTATE]]
-** 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 is only available when the SQLITE_TEST
-** compile-time option is used.
-**
-**
- [[SQLITE_FCNTL_SIZE_HINT]]
-** 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.
-**
-**
- [[SQLITE_FCNTL_SIZE_LIMIT]]
-** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
-** implements [sqlite3_deserialize()] to set an upper bound on the size
-** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
-** If the integer pointed to is negative, then it is filled in with the
-** current limit. Otherwise the limit is set to the larger of the value
-** of the integer pointed to and the current database size. The integer
-** pointed to is set to the new limit.
-**
-**
- [[SQLITE_FCNTL_CHUNK_SIZE]]
-** 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.
-**
-**
- [[SQLITE_FCNTL_FILE_POINTER]]
-** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
-** to the [sqlite3_file] object associated with a particular database
-** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
-**
-**
- [[SQLITE_FCNTL_JOURNAL_POINTER]]
-** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
-** to the [sqlite3_file] object associated with the journal file (either
-** the [rollback journal] or the [write-ahead log]) for a particular database
-** connection. See also [SQLITE_FCNTL_FILE_POINTER].
-**
-**
- [[SQLITE_FCNTL_SYNC_OMITTED]]
-** No longer in use.
-**
-**
- [[SQLITE_FCNTL_SYNC]]
-** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
-** sent to the VFS immediately before the xSync method is invoked on a
-** database file descriptor. Or, if the xSync method is not invoked
-** because the user has configured SQLite with
-** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
-** of the xSync method. In most cases, the pointer argument passed with
-** this file-control is NULL. However, if the database file is being synced
-** as part of a multi-database commit, the argument points to a nul-terminated
-** string containing the transactions master-journal file name. VFSes that
-** do not need this signal 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.
-**
-**
- [[SQLITE_FCNTL_COMMIT_PHASETWO]]
-** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
-** and sent to the VFS after a transaction has been committed immediately
-** but before the database is unlocked. VFSes that do not need this signal
-** 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.
-**
-**
- [[SQLITE_FCNTL_WIN32_AV_RETRY]]
-** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
-** retry counts and intervals for certain disk I/O operations for the
-** windows [VFS] in order to provide robustness in the presence of
-** anti-virus programs. By default, the windows VFS will retry file read,
-** file write, and file delete operations up to 10 times, with a delay
-** of 25 milliseconds before the first retry and with the delay increasing
-** by an additional 25 milliseconds with each subsequent retry. This
-** opcode allows these two values (10 retries and 25 milliseconds of delay)
-** to be adjusted. The values are changed for all database connections
-** within the same process. The argument is a pointer to an array of two
-** integers where the first integer is the new retry count and the second
-** integer is the delay. If either integer is negative, then the setting
-** is not changed but instead the prior value of that setting is written
-** into the array entry, allowing the current retry settings to be
-** interrogated. The zDbName parameter is ignored.
-**
-**
- [[SQLITE_FCNTL_PERSIST_WAL]]
-** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
-** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
-** write ahead log ([WAL file]) and shared memory
-** files used for transaction control
-** are automatically deleted when the latest connection to the database
-** closes. Setting persistent WAL mode causes those files to persist after
-** close. Persisting the files is useful when other processes that do not
-** have write permission on the directory containing the database file want
-** to read the database file, as the WAL and shared memory files must exist
-** in order for the database to be readable. The fourth parameter to
-** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
-** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
-** WAL mode. If the integer is -1, then it is overwritten with the current
-** WAL persistence setting.
-**
-**
- [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
-** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
-** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
-** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
-** xDeviceCharacteristics methods. The fourth parameter to
-** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
-** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
-** mode. If the integer is -1, then it is overwritten with the current
-** zero-damage mode setting.
-**
-**
- [[SQLITE_FCNTL_OVERWRITE]]
-** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
-** a write transaction to indicate that, unless it is rolled back for some
-** reason, the entire database file will be overwritten by the current
-** transaction. This is used by VACUUM operations.
-**
-**
- [[SQLITE_FCNTL_VFSNAME]]
-** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
-** all [VFSes] in the VFS stack. The names are of all VFS shims and the
-** final bottom-level VFS are written into memory obtained from
-** [sqlite3_malloc()] and the result is stored in the char* variable
-** that the fourth parameter of [sqlite3_file_control()] points to.
-** The caller is responsible for freeing the memory when done. As with
-** all file-control actions, there is no guarantee that this will actually
-** do anything. Callers should initialize the char* variable to a NULL
-** pointer in case this file-control is not implemented. This file-control
-** is intended for diagnostic use only.
-**
-**
- [[SQLITE_FCNTL_VFS_POINTER]]
-** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
-** [VFSes] currently in use. ^(The argument X in
-** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
-** of type "[sqlite3_vfs] **". This opcodes will set *X
-** to a pointer to the top-level VFS.)^
-** ^When there are multiple VFS shims in the stack, this opcode finds the
-** upper-most shim only.
-**
-**
- [[SQLITE_FCNTL_PRAGMA]]
-** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
-** file control is sent to the open [sqlite3_file] object corresponding
-** to the database file to which the pragma statement refers. ^The argument
-** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
-** pointers to strings (char**) in which the second element of the array
-** is the name of the pragma and the third element is the argument to the
-** pragma or NULL if the pragma has no argument. ^The handler for an
-** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
-** of the char** argument point to a string obtained from [sqlite3_mprintf()]
-** or the equivalent and that string will become the result of the pragma or
-** the error message if the pragma fails. ^If the
-** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
-** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
-** file control returns [SQLITE_OK], then the parser assumes that the
-** VFS has handled the PRAGMA itself and the parser generates a no-op
-** prepared statement if result string is NULL, or that returns a copy
-** of the result string if the string is non-NULL.
-** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
-** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
-** that the VFS encountered an error while handling the [PRAGMA] and the
-** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
-** file control occurs at the beginning of pragma statement analysis and so
-** it is able to override built-in [PRAGMA] statements.
-**
-**
- [[SQLITE_FCNTL_BUSYHANDLER]]
-** ^The [SQLITE_FCNTL_BUSYHANDLER]
-** file-control may be invoked by SQLite on the database file handle
-** shortly after it is opened in order to provide a custom VFS with access
-** to the connections busy-handler callback. The argument is of type (void **)
-** - an array of two (void *) values. The first (void *) actually points
-** to a function of type (int (*)(void *)). In order to invoke the connections
-** busy-handler, this function should be invoked with the second (void *) in
-** the array as the only argument. If it returns non-zero, then the operation
-** should be retried. If it returns zero, the custom VFS should abandon the
-** current operation.
-**
-**
- [[SQLITE_FCNTL_TEMPFILENAME]]
-** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
-** to have SQLite generate a
-** temporary filename using the same algorithm that is followed to generate
-** temporary filenames for TEMP tables and other internal uses. The
-** argument should be a char** which will be filled with the filename
-** written into memory obtained from [sqlite3_malloc()]. The caller should
-** invoke [sqlite3_free()] on the result to avoid a memory leak.
-**
-**
- [[SQLITE_FCNTL_MMAP_SIZE]]
-** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
-** maximum number of bytes that will be used for memory-mapped I/O.
-** The argument is a pointer to a value of type sqlite3_int64 that
-** is an advisory maximum number of bytes in the file to memory map. The
-** pointer is overwritten with the old value. The limit is not changed if
-** the value originally pointed to is negative, and so the current limit
-** can be queried by passing in a pointer to a negative number. This
-** file-control is used internally to implement [PRAGMA mmap_size].
-**
-**
- [[SQLITE_FCNTL_TRACE]]
-** The [SQLITE_FCNTL_TRACE] file control provides advisory information
-** to the VFS about what the higher layers of the SQLite stack are doing.
-** This file control is used by some VFS activity tracing [shims].
-** The argument is a zero-terminated string. Higher layers in the
-** SQLite stack may generate instances of this file control if
-** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
-**
-**
- [[SQLITE_FCNTL_HAS_MOVED]]
-** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
-** pointer to an integer and it writes a boolean into that integer depending
-** on whether or not the file has been renamed, moved, or deleted since it
-** was first opened.
-**
-**
- [[SQLITE_FCNTL_WIN32_GET_HANDLE]]
-** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
-** underlying native file handle associated with a file handle. This file
-** control interprets its argument as a pointer to a native file handle and
-** writes the resulting value there.
-**
-**
- [[SQLITE_FCNTL_WIN32_SET_HANDLE]]
-** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
-** opcode causes the xFileControl method to swap the file handle with the one
-** pointed to by the pArg argument. This capability is used during testing
-** and only needs to be supported when SQLITE_TEST is defined.
-**
-**
- [[SQLITE_FCNTL_WAL_BLOCK]]
-** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
-** be advantageous to block on the next WAL lock if the lock is not immediately
-** available. The WAL subsystem issues this signal during rare
-** circumstances in order to fix a problem with priority inversion.
-** Applications should not use this file-control.
-**
-**
- [[SQLITE_FCNTL_ZIPVFS]]
-** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
-** VFS should return SQLITE_NOTFOUND for this opcode.
-**
-**
- [[SQLITE_FCNTL_RBU]]
-** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
-** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
-** this opcode.
-**
-**
- [[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
-** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
-** the file descriptor is placed in "batch write mode", which
-** means all subsequent write operations will be deferred and done
-** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
-** that do not support batch atomic writes will return SQLITE_NOTFOUND.
-** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
-** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
-** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
-** no VFS interface calls on the same [sqlite3_file] file descriptor
-** except for calls to the xWrite method and the xFileControl method
-** with [SQLITE_FCNTL_SIZE_HINT].
-**
-**
- [[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
-** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to
-** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
-** This file control returns [SQLITE_OK] if and only if the writes were
-** all performed successfully and have been committed to persistent storage.
-** ^Regardless of whether or not it is successful, this file control takes
-** the file descriptor out of batch write mode so that all subsequent
-** write operations are independent.
-** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
-** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
-**
-**
- [[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
-** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to
-** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
-** ^This file control takes the file descriptor out of batch write mode
-** so that all subsequent write operations are independent.
-** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
-** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
-**
-**
- [[SQLITE_FCNTL_LOCK_TIMEOUT]]
-** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
-** a file lock using the xLock or xShmLock methods of the VFS to wait
-** for up to M milliseconds before failing, where M is the single
-** unsigned integer parameter.
-**
-**
- [[SQLITE_FCNTL_DATA_VERSION]]
-** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
-** a database file. The argument is a pointer to a 32-bit unsigned integer.
-** The "data version" for the pager is written into the pointer. The
-** "data version" changes whenever any change occurs to the corresponding
-** database file, either through SQL statements on the same database
-** connection or through transactions committed by separate database
-** connections possibly in other processes. The [sqlite3_total_changes()]
-** interface can be used to find if any database on the connection has changed,
-** but that interface responds to changes on TEMP as well as MAIN and does
-** not provide a mechanism to detect changes to MAIN only. Also, the
-** [sqlite3_total_changes()] interface responds to internal changes only and
-** omits changes made by other database connections. The
-** [PRAGMA data_version] command provide a mechanism to detect changes to
-** a single attached database that occur due to other database connections,
-** but omits changes implemented by the database connection on which it is
-** called. This file control is the only mechanism to detect changes that
-** happen either internally or externally and that are associated with
-** a particular attached database.
-**
-*/
-#define SQLITE_FCNTL_LOCKSTATE 1
-#define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
-#define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
-#define SQLITE_FCNTL_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
-#define SQLITE_FCNTL_WIN32_AV_RETRY 9
-#define SQLITE_FCNTL_PERSIST_WAL 10
-#define SQLITE_FCNTL_OVERWRITE 11
-#define SQLITE_FCNTL_VFSNAME 12
-#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
-#define SQLITE_FCNTL_PRAGMA 14
-#define SQLITE_FCNTL_BUSYHANDLER 15
-#define SQLITE_FCNTL_TEMPFILENAME 16
-#define SQLITE_FCNTL_MMAP_SIZE 18
-#define SQLITE_FCNTL_TRACE 19
-#define SQLITE_FCNTL_HAS_MOVED 20
-#define SQLITE_FCNTL_SYNC 21
-#define SQLITE_FCNTL_COMMIT_PHASETWO 22
-#define SQLITE_FCNTL_WIN32_SET_HANDLE 23
-#define SQLITE_FCNTL_WAL_BLOCK 24
-#define SQLITE_FCNTL_ZIPVFS 25
-#define SQLITE_FCNTL_RBU 26
-#define SQLITE_FCNTL_VFS_POINTER 27
-#define SQLITE_FCNTL_JOURNAL_POINTER 28
-#define SQLITE_FCNTL_WIN32_GET_HANDLE 29
-#define SQLITE_FCNTL_PDB 30
-#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
-#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
-#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
-#define SQLITE_FCNTL_LOCK_TIMEOUT 34
-#define SQLITE_FCNTL_DATA_VERSION 35
-#define SQLITE_FCNTL_SIZE_LIMIT 36
-
-/* deprecated names */
-#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
-#define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
-#define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
-
-
-/*
-** 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: Loadable Extension Thunk
-**
-** A pointer to the opaque sqlite3_api_routines structure is passed as
-** the third parameter to entry points of [loadable extensions]. This
-** structure must be typedefed in order to work around compiler warnings
-** on some platforms.
-*/
-typedef struct sqlite3_api_routines sqlite3_api_routines;
-
-/*
-** 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 VFS interface is sometimes extended by adding new methods onto
-** the end. Each time such an extension occurs, the iVersion field
-** is incremented. The iVersion value started out as 1 in
-** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
-** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
-** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
-** may be appended to the sqlite3_vfs object and the iVersion value
-** may increase again in future versions of SQLite.
-** Note that the structure
-** of the sqlite3_vfs object changes in the transition from
-** SQLite [version 3.5.9] to [version 3.6.0] on [dateof: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
-** 11 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 SQLITE_ACCESS_READ
-** flag is never actually used and is not implemented in the built-in
-** VFSes of SQLite. The file is named by the second argument and can be a
-** directory. The xAccess method returns [SQLITE_OK] on success or some
-** non-zero error code if there is an I/O error or if the name of
-** the file given in the second argument is illegal. If SQLITE_OK
-** is returned, then non-zero or zero is written into *pResOut to indicate
-** whether or not the file is accessible.
-**
-** ^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 */
- const char *zName; /* Name of this virtual file system */
- void *pAppData; /* Pointer to application-specific data */
- int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
- int flags, int *pOutFlags);
- int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
- int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
- int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
- void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
- void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
- void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
- void (*xDlClose)(sqlite3_vfs*, void*);
- int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
- int (*xSleep)(sqlite3_vfs*, int microseconds);
- int (*xCurrentTime)(sqlite3_vfs*, double*);
- int (*xGetLastError)(sqlite3_vfs*, int, char *);
- /*
- ** 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.
- ** Those below are for version 3 and greater.
- */
- int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
- sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
- const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
- /*
- ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
- ** New fields may be appended in future versions. The iVersion
- ** value will increment whenever this happens.
- */
-};
-
-/*
-** 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 */
-
-/*
-** 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 on 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
-
-/*
-** 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
-
-
-/*
-** 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 ensure that no other SQLite interfaces are invoked by other
-** threads while sqlite3_config() is running.
-**
-** The sqlite3_config() interface
-** 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
-** METHOD: sqlite3
-**
-** 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, xRealloc, and xFree methods must work like the
-** malloc(), realloc() and free() functions from the standard C library.
-** ^SQLite guarantees that the second argument to
-** xRealloc is always a value returned by a prior call to xRoundup.
-**
-** 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() */
-};
-
-/*
-** 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
-** - ^(The SQLITE_CONFIG_MALLOC 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
-** - ^(The SQLITE_CONFIG_GETMALLOC 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_SMALL_MALLOC]] - SQLITE_CONFIG_SMALL_MALLOC
-** - ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
-** type int, interpreted as a boolean, which if true provides a hint to
-** SQLite that it should avoid large memory allocations if possible.
-** SQLite will run faster if it is free to make large memory allocations,
-** but some application might prefer to run slower in exchange for
-** guarantees about memory fragmentation that are possible if large
-** allocations are avoided. This hint is normally off.
-**
-**
-** [[SQLITE_CONFIG_MEMSTATUS]] - SQLITE_CONFIG_MEMSTATUS
-** - ^The SQLITE_CONFIG_MEMSTATUS 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_status64()]
-**
)^
-** ^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
-** - The SQLITE_CONFIG_SCRATCH option is no longer used.
-**
-**
-** [[SQLITE_CONFIG_PAGECACHE]] - SQLITE_CONFIG_PAGECACHE
-** - ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
-** that SQLite can use for the database page cache with the default page
-** cache implementation.
-** This configuration option is a no-op if an application-define page
-** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
-** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
-** 8-byte aligned memory (pMem), the size of each page cache line (sz),
-** and the number of cache lines (N).
-** The sz argument should be the size of the largest database page
-** (a power of two between 512 and 65536) plus some extra bytes for each
-** page header. ^The number of extra bytes needed by the page header
-** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
-** ^It is harmless, apart from the wasted memory,
-** for the sz parameter to be larger than necessary. The pMem
-** argument must be either a NULL pointer or a pointer to an 8-byte
-** aligned block of memory of at least sz*N bytes, otherwise
-** subsequent behavior is undefined.
-** ^When pMem is not NULL, SQLite will strive to use the memory provided
-** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
-** a page cache line is larger than sz bytes or if all of the pMem buffer
-** is exhausted.
-** ^If pMem is NULL and N is non-zero, then each database connection
-** does an initial bulk allocation for page cache memory
-** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
-** of -1024*N bytes if N is negative, . ^If additional
-** page cache memory is needed beyond what is provided by the initial
-** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
-** additional cache line.
-**
-** [[SQLITE_CONFIG_HEAP]] - SQLITE_CONFIG_HEAP
-** - ^The SQLITE_CONFIG_HEAP 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_PAGECACHE].
-** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
-** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
-** [SQLITE_ERROR] if invoked otherwise.
-** ^There are three arguments to SQLITE_CONFIG_HEAP:
-** 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 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
-** - ^(The SQLITE_CONFIG_MUTEX 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
-** - ^(The SQLITE_CONFIG_GETMUTEX 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
-** - ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
-** the default size of lookaside memory 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.)^ ^(SQLITE_CONFIG_LOOKASIDE
-** sets the default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
-** option to [sqlite3_db_config()] can be used to change the lookaside
-** configuration on individual connections.)^
-**
-** [[SQLITE_CONFIG_PCACHE2]] - SQLITE_CONFIG_PCACHE2
-** - ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
-** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
-** the interface to a custom page cache implementation.)^
-** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.
-**
-** [[SQLITE_CONFIG_GETPCACHE2]] - SQLITE_CONFIG_GETPCACHE2
-** - ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
-** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
-** the current page cache implementation into that object.)^
-**
-** [[SQLITE_CONFIG_LOG]] - SQLITE_CONFIG_LOG
-** - The SQLITE_CONFIG_LOG option is used to configure the SQLite
-** global [error 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
-**
- ^(The SQLITE_CONFIG_URI 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.)^
-**
-** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
- SQLITE_CONFIG_COVERING_INDEX_SCAN
-**
- ^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
-** argument which is interpreted as a boolean in order to enable or disable
-** the use of covering indices for full table scans in the query optimizer.
-** ^The default setting is determined
-** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
-** if that compile-time option is omitted.
-** The ability to disable the use of covering indices for full table scans
-** is because some incorrectly coded legacy applications might malfunction
-** when the optimization is enabled. Providing the ability to
-** disable the optimization allows the older, buggy application code to work
-** without change even with newer versions of SQLite.
-**
-** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
-**
- SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
-**
- These options are obsolete and should not be used by new code.
-** They are retained for backwards compatibility but are now no-ops.
-**
-**
-** [[SQLITE_CONFIG_SQLLOG]]
-** - SQLITE_CONFIG_SQLLOG
-**
- This option is only available if sqlite is compiled with the
-** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
-** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
-** The second should be of type (void*). The callback is invoked by the library
-** in three separate circumstances, identified by the value passed as the
-** fourth parameter. If the fourth parameter is 0, then the database connection
-** passed as the second argument has just been opened. The third argument
-** points to a buffer containing the name of the main database file. If the
-** fourth parameter is 1, then the SQL statement that the third parameter
-** points to has just been executed. Or, if the fourth parameter is 2, then
-** the connection being passed as the second parameter is being closed. The
-** third parameter is passed NULL In this case. An example of using this
-** configuration option can be seen in the "test_sqllog.c" source file in
-** the canonical SQLite source tree.
-**
-** [[SQLITE_CONFIG_MMAP_SIZE]]
-** - SQLITE_CONFIG_MMAP_SIZE
-**
- ^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
-** that are the default mmap size limit (the default setting for
-** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
-** ^The default setting can be overridden by each database connection using
-** either the [PRAGMA mmap_size] command, or by using the
-** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
-** will be silently truncated if necessary so that it does not exceed the
-** compile-time maximum mmap size set by the
-** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
-** ^If either argument to this option is negative, then that argument is
-** changed to its compile-time default.
-**
-** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
-**
- SQLITE_CONFIG_WIN32_HEAPSIZE
-**
- ^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
-** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
-** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
-** that specifies the maximum size of the created heap.
-**
-** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
-**
- SQLITE_CONFIG_PCACHE_HDRSZ
-**
- ^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
-** is a pointer to an integer and writes into that integer the number of extra
-** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
-** The amount of extra space required can change depending on the compiler,
-** target platform, and SQLite version.
-**
-** [[SQLITE_CONFIG_PMASZ]]
-**
- SQLITE_CONFIG_PMASZ
-**
- ^The SQLITE_CONFIG_PMASZ option takes a single parameter which
-** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
-** sorter to that integer. The default minimum PMA Size is set by the
-** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
-** to help with sort operations when multithreaded sorting
-** is enabled (using the [PRAGMA threads] command) and the amount of content
-** to be sorted exceeds the page size times the minimum of the
-** [PRAGMA cache_size] setting and this value.
-**
-** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
-**
- SQLITE_CONFIG_STMTJRNL_SPILL
-**
- ^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
-** becomes the [statement journal] spill-to-disk threshold.
-** [Statement journals] are held in memory until their size (in bytes)
-** exceeds this threshold, at which point they are written to disk.
-** Or if the threshold is -1, statement journals are always held
-** exclusively in memory.
-** Since many statement journals never become large, setting the spill
-** threshold to a value such as 64KiB can greatly reduce the amount of
-** I/O required to support statement rollback.
-** The default value for this setting is controlled by the
-** [SQLITE_STMTJRNL_SPILL] compile-time option.
-**
-** [[SQLITE_CONFIG_SORTERREF_SIZE]]
-**
- SQLITE_CONFIG_SORTERREF_SIZE
-**
- The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
-** of type (int) - the new value of the sorter-reference size threshold.
-** Usually, when SQLite uses an external sort to order records according
-** to an ORDER BY clause, all fields required by the caller are present in the
-** sorted records. However, if SQLite determines based on the declared type
-** of a table column that its values are likely to be very large - larger
-** than the configured sorter-reference size threshold - then a reference
-** is stored in each sorted record and the required column values loaded
-** from the database as records are returned in sorted order. The default
-** value for this option is to never use this optimization. Specifying a
-** negative value for this option restores the default behaviour.
-** This option is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
-**
-** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
-**
- SQLITE_CONFIG_MEMDB_MAXSIZE
-**
- The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
-** [sqlite3_int64] parameter which is the default maximum size for an in-memory
-** database created using [sqlite3_deserialize()]. This default maximum
-** size can be adjusted up or down for individual databases using the
-** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
-** configuration setting is never used, then the default maximum is determined
-** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
-** compile-time option is not set, then the default maximum is 1073741824.
-**
-*/
-#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 /* No longer used */
-#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 /* no-op */
-#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
-#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
-#define SQLITE_CONFIG_URI 17 /* int */
-#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
-#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
-#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
-#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
-#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
-#define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
-#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
-#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
-#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
-#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
-#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
-#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
-
-/*
-** 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]]
-** - 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]]
-** - 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]]
-** - 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.
-**
-** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
-** - SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
-** - ^This option is used to enable or disable the
-** [fts3_tokenizer()] function which is part of the
-** [FTS3] full-text search engine extension.
-** There should be two additional arguments.
-** The first argument is an integer which is 0 to disable fts3_tokenizer() or
-** positive to enable fts3_tokenizer() 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 fts3_tokenizer is disabled or enabled
-** following this call. The second parameter may be a NULL pointer, in
-** which case the new setting is not reported back.
-**
-** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
-** - SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
-** - ^This option is used to enable or disable the [sqlite3_load_extension()]
-** interface independently of the [load_extension()] SQL function.
-** The [sqlite3_enable_load_extension()] API enables or disables both the
-** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
-** There should be two additional arguments.
-** When the first argument to this interface is 1, then only the C-API is
-** enabled and the SQL function remains disabled. If the first argument to
-** this interface is 0, then both the C-API and the SQL function are disabled.
-** If the first argument is -1, then no changes are made to state of either the
-** C-API or the SQL function.
-** The second parameter is a pointer to an integer into which
-** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
-** is disabled or enabled following this call. The second parameter may
-** be a NULL pointer, in which case the new setting is not reported back.
-**
-**
-** [[SQLITE_DBCONFIG_MAINDBNAME]] - SQLITE_DBCONFIG_MAINDBNAME
-** - ^This option is used to change the name of the "main" database
-** schema. ^The sole argument is a pointer to a constant UTF8 string
-** which will become the new schema name in place of "main". ^SQLite
-** does not make a copy of the new main schema name string, so the application
-** must ensure that the argument passed into this DBCONFIG option is unchanged
-** until after the database connection closes.
-**
-**
-** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
-** - SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
-** - Usually, when a database in wal mode is closed or detached from a
-** database handle, SQLite checks if this will mean that there are now no
-** connections at all to the database. If so, it performs a checkpoint
-** operation before closing the connection. This option may be used to
-** override this behaviour. The first parameter passed to this operation
-** is an integer - positive to disable checkpoints-on-close, or zero (the
-** default) to enable them, and 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 checkpoints-on-close
-** have been disabled - 0 if they are not disabled, 1 if they are.
-**
-**
-** [[SQLITE_DBCONFIG_ENABLE_QPSG]] - SQLITE_DBCONFIG_ENABLE_QPSG
-** - ^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
-** the [query planner stability guarantee] (QPSG). When the QPSG is active,
-** a single SQL query statement will always use the same algorithm regardless
-** of values of [bound parameters].)^ The QPSG disables some query optimizations
-** that look at the values of bound parameters, which can make some queries
-** slower. But the QPSG has the advantage of more predictable behavior. With
-** the QPSG active, SQLite will always use the same query plan in the field as
-** was used during testing in the lab.
-** The first argument to this setting is an integer which is 0 to disable
-** the QPSG, positive to enable QPSG, 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 the QPSG is disabled or enabled
-** following this call.
-**
-**
-** [[SQLITE_DBCONFIG_TRIGGER_EQP]] - SQLITE_DBCONFIG_TRIGGER_EQP
-** - By default, the output of EXPLAIN QUERY PLAN commands does not
-** include output for any operations performed by trigger programs. This
-** option is used to set or clear (the default) a flag that governs this
-** behavior. The first parameter passed to this operation is an integer -
-** positive to enable output for trigger programs, or zero to disable it,
-** 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 output-for-triggers has been disabled - 0 if
-** it is not disabled, 1 if it is.
-**
-**
-** [[SQLITE_DBCONFIG_RESET_DATABASE]] - SQLITE_DBCONFIG_RESET_DATABASE
-** - Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
-** [VACUUM] in order to reset a database back to an empty database
-** with no schema and no content. The following process works even for
-** a badly corrupted database file:
-**
-** - If the database connection is newly opened, make sure it has read the
-** database schema by preparing then discarding some query against the
-** database, or calling sqlite3_table_column_metadata(), ignoring any
-** errors. This step is only necessary if the application desires to keep
-** the database in WAL mode after the reset if it was in WAL mode before
-** the reset.
-**
- sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
-**
- [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
-**
- sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
-**
-** Because resetting a database is destructive and irreversible, the
-** process requires the use of this obscure API and multiple steps to help
-** ensure that it does not happen by accident.
-**
-** [[SQLITE_DBCONFIG_DEFENSIVE]] - SQLITE_DBCONFIG_DEFENSIVE
-** - The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
-** "defensive" flag for a database connection. When the defensive
-** flag is enabled, language features that allow ordinary SQL to
-** deliberately corrupt the database file are disabled. The disabled
-** features include but are not limited to the following:
-**
-** - The [PRAGMA writable_schema=ON] statement.
-**
- The [PRAGMA journal_mode=OFF] statement.
-**
- Writes to the [sqlite_dbpage] virtual table.
-**
- Direct writes to [shadow tables].
-**
-**
-**
-** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] - SQLITE_DBCONFIG_WRITABLE_SCHEMA
-** - The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
-** "writable_schema" flag. This has the same effect and is logically equivalent
-** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
-** The first argument to this setting is an integer which is 0 to disable
-** the writable_schema, positive to enable writable_schema, 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 the writable_schema
-** is enabled or disabled following this call.
-**
-**
-** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
-** - SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
-** - The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
-** the legacy behavior of the [ALTER TABLE RENAME] command such it
-** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
-** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
-** additional information. This feature can also be turned on and off
-** using the [PRAGMA legacy_alter_table] statement.
-**
-**
-** [[SQLITE_DBCONFIG_DQS_DML]]
-** - SQLITE_DBCONFIG_DQS_DML
-**
- The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
-** the legacy [double-quoted string literal] misfeature for DML statement
-** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
-** default value of this setting is determined by the [-DSQLITE_DQS]
-** compile-time option.
-**
-**
-** [[SQLITE_DBCONFIG_DQS_DDL]]
-** - SQLITE_DBCONFIG_DQS_DDL
-**
- The SQLITE_DBCONFIG_DQS option activates or deactivates
-** the legacy [double-quoted string literal] misfeature for DDL statements,
-** such as CREATE TABLE and CREATE INDEX. The
-** default value of this setting is determined by the [-DSQLITE_DQS]
-** compile-time option.
-**
-**
-*/
-#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
-#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
-#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
-#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
-#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
-#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
-#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
-#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
-#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
-#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
-#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
-#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
-#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
-#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
-#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
-#define SQLITE_DBCONFIG_MAX 1014 /* Largest DBCONFIG */
-
-/*
-** CAPI3REF: Enable Or Disable Extended Result Codes
-** METHOD: sqlite3
-**
-** ^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
-** METHOD: sqlite3
-**
-** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
-** 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.
-**
-** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
-** the most recent successful [INSERT] into a rowid table or [virtual table]
-** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
-** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
-** on the database connection D, then sqlite3_last_insert_rowid(D) returns
-** zero.
-**
-** As well as being set automatically as rows are inserted into database
-** tables, the value returned by this function may be set explicitly by
-** [sqlite3_set_last_insert_rowid()]
-**
-** Some virtual table implementations may INSERT rows into rowid tables as
-** part of committing a transaction (e.g. to flush data accumulated in memory
-** to disk). In this case subsequent calls to this function return the rowid
-** associated with these internal INSERT operations, which leads to
-** unintuitive results. Virtual table implementations that do write to rowid
-** tables in this way can avoid this problem by restoring the original
-** rowid value using [sqlite3_set_last_insert_rowid()] before returning
-** control to the user.
-**
-** ^(If an [INSERT] occurs within a trigger then this routine will
-** return the [rowid] of the inserted row as long as the trigger is
-** running. Once the trigger program ends, the value returned
-** by this routine reverts to what it was before the trigger was fired.)^
-**
-** ^An [INSERT] that fails due to a constraint violation is not a
-** successful [INSERT] and does not change the value returned by this
-** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
-** and INSERT OR ABORT make no changes to the return value of this
-** routine when their insertion fails. ^(When INSERT OR REPLACE
-** encounters a constraint violation, it does not fail. The
-** INSERT continues to completion after deleting rows that caused
-** the constraint problem so INSERT OR REPLACE will always change
-** the return value of this interface.)^
-**
-** ^For the purposes of this routine, an [INSERT] is considered to
-** be successful even if it is subsequently rolled back.
-**
-** 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: Set the Last Insert Rowid value.
-** METHOD: sqlite3
-**
-** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
-** set the value returned by calling sqlite3_last_insert_rowid(D) to R
-** without inserting a row into the database.
-*/
-SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
-
-/*
-** CAPI3REF: Count The Number Of Rows Modified
-** METHOD: sqlite3
-**
-** ^This function returns the number of rows modified, inserted or
-** deleted by the most recently completed INSERT, UPDATE or DELETE
-** statement on the database connection specified by the only parameter.
-** ^Executing any other type of SQL statement does not modify the value
-** returned by this function.
-**
-** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
-** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
-** [foreign key actions] or [REPLACE] constraint resolution are not counted.
-**
-** Changes to a view that are intercepted by
-** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
-** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
-** DELETE statement run on a view is always zero. Only changes made to real
-** tables are counted.
-**
-** Things are more complicated if the sqlite3_changes() function is
-** executed while a trigger program is running. This may happen if the
-** program uses the [changes() SQL function], or if some other callback
-** function invokes sqlite3_changes() directly. Essentially:
-**
-**
-** - ^(Before entering a trigger program the value returned by
-** sqlite3_changes() function is saved. After the trigger program
-** has finished, the original value is restored.)^
-**
-**
- ^(Within a trigger program each INSERT, UPDATE and DELETE
-** statement sets the value returned by sqlite3_changes()
-** upon completion as normal. Of course, this value will not include
-** any changes performed by sub-triggers, as the sqlite3_changes()
-** value will be saved and restored after each sub-trigger has run.)^
-**
-**
-** ^This means that if the changes() SQL function (or similar) is used
-** by the first INSERT, UPDATE or DELETE statement within a trigger, it
-** returns the value as set when the calling statement began executing.
-** ^If it is used by the second or subsequent such statement within a trigger
-** program, the value returned reflects the number of rows modified by the
-** previous INSERT, UPDATE or DELETE statement within the same trigger.
-**
-** 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.
-**
-** See also:
-**
-** - the [sqlite3_total_changes()] interface
-**
- the [count_changes pragma]
-**
- the [changes() SQL function]
-**
- the [data_version pragma]
-**
-*/
-SQLITE_API int sqlite3_changes(sqlite3*);
-
-/*
-** CAPI3REF: Total Number Of Rows Modified
-** METHOD: sqlite3
-**
-** ^This function returns the total number of rows inserted, modified or
-** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
-** since the database connection was opened, including those executed as
-** part of trigger programs. ^Executing any other type of SQL statement
-** does not affect the value returned by sqlite3_total_changes().
-**
-** ^Changes made as part of [foreign key actions] are included in the
-** count, but those made as part of REPLACE constraint resolution are
-** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
-** are not counted.
-**
-** The [sqlite3_total_changes(D)] interface only reports the number
-** of rows that changed due to SQL statement run against database
-** connection D. Any changes by other database connections are ignored.
-** To detect changes against a database file from other database
-** connections use the [PRAGMA data_version] command or the
-** [SQLITE_FCNTL_DATA_VERSION] [file control].
-**
-** 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.
-**
-** See also:
-**
-** - the [sqlite3_changes()] interface
-**
- the [count_changes pragma]
-**
- the [changes() SQL function]
-**
- the [data_version pragma]
-**
- the [SQLITE_FCNTL_DATA_VERSION] [file control]
-**
-*/
-SQLITE_API int sqlite3_total_changes(sqlite3*);
-
-/*
-** CAPI3REF: Interrupt A Long-Running Query
-** METHOD: sqlite3
-**
-** ^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.
-*/
-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(const char *sql);
-SQLITE_API int sqlite3_complete16(const void *sql);
-
-/*
-** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
-** KEYWORDS: {busy-handler callback} {busy handler}
-** METHOD: sqlite3
-**
-** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
-** that might be invoked with argument P whenever
-** an attempt is made to access a database table associated with
-** [database connection] D when another thread
-** or process has the table locked.
-** The sqlite3_busy_handler() interface is used to implement
-** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
-**
-** ^If the busy callback is NULL, then [SQLITE_BUSY]
-** 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 previously for the same locking event. ^If the
-** busy callback returns 0, then no additional attempts are made to
-** access the database and [SQLITE_BUSY] is returned
-** to the application.
-** ^If the callback returns non-zero, then another attempt
-** is made to access the database 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]
-** to the application 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.
-**
-** ^(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()]
-** or evaluating [PRAGMA busy_timeout=N] will change the
-** busy handler and thus clear any previously set busy handler.
-**
-** The busy callback should not take any actions which modify the
-** database connection that invoked the busy handler. In other words,
-** the busy handler is not reentrant. 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
-** METHOD: sqlite3
-**
-** ^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].
-**
-** ^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] at any given moment. If another busy handler
-** was defined (using [sqlite3_busy_handler()]) prior to calling
-** this routine, that other busy handler is cleared.)^
-**
-** See also: [PRAGMA busy_timeout]
-*/
-SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
-
-/*
-** CAPI3REF: Convenience Routines For Running Queries
-** METHOD: sqlite3
-**
-** 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 */
- const char *zSql, /* SQL to be evaluated */
- char ***pazResult, /* Results of the query */
- int *pnRow, /* Number of result rows written here */
- int *pnColumn, /* Number of result columns written here */
- char **pzErrmsg /* Error msg written here */
-);
-SQLITE_API void sqlite3_free_table(char **result);
-
-/*
-** CAPI3REF: Formatted String Printing Functions
-**
-** These routines are work-alikes of the "printf()" family of functions
-** from the standard C library.
-** These routines understand most of the common formatting options from
-** the standard library printf()
-** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
-** See the [built-in printf()] documentation for details.
-**
-** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
-** results into memory obtained from [sqlite3_malloc64()].
-** The strings returned by these two routines should be
-** released by [sqlite3_free()]. ^Both routines return a
-** NULL pointer if [sqlite3_malloc64()] 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().
-**
-** See also: [built-in printf()], [printf() SQL function]
-*/
-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.
-**
-** ^The sqlite3_malloc64(N) routine works just like
-** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
-** of a signed 32-bit integer.
-**
-** ^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(X,N) interface attempts to resize a
-** prior memory allocation X to be at least N bytes.
-** ^If the X parameter to sqlite3_realloc(X,N)
-** is a NULL pointer then its behavior is identical to calling
-** sqlite3_malloc(N).
-** ^If the N parameter to sqlite3_realloc(X,N) is zero or
-** negative then the behavior is exactly the same as calling
-** sqlite3_free(X).
-** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
-** of at least N bytes in size or NULL if insufficient memory is available.
-** ^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(X,N) and the prior allocation is freed.
-** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
-** prior allocation is not freed.
-**
-** ^The sqlite3_realloc64(X,N) interfaces works the same as
-** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
-** of a 32-bit signed integer.
-**
-** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
-** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
-** sqlite3_msize(X) returns the size of that memory allocation in bytes.
-** ^The value returned by sqlite3_msize(X) might be larger than the number
-** of bytes requested when X was allocated. ^If X is a NULL pointer then
-** sqlite3_msize(X) returns zero. If X points to something that is not
-** the beginning of memory allocation, or if it points to a formerly
-** valid memory allocation that has now been freed, then the behavior
-** of sqlite3_msize(X) is undefined and possibly harmful.
-**
-** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
-** sqlite3_malloc64(), and sqlite3_realloc64()
-** 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.
-**
-** Prior to SQLite version 3.7.10, the Windows OS interface layer called
-** 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 were detected, but
-** they were 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_malloc64(sqlite3_uint64);
-SQLITE_API void *sqlite3_realloc(void*, int);
-SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
-SQLITE_API void sqlite3_free(void*);
-SQLITE_API sqlite3_uint64 sqlite3_msize(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 P parameter can be a NULL pointer.
-**
-** ^If this routine has not been previously called or if the previous
-** call had N less than one or a NULL pointer for P, then the PRNG is
-** seeded using randomness obtained from the xRandomness method of
-** the default [sqlite3_vfs] object.
-** ^If the previous call to this routine had an N of 1 or more and a
-** non-NULL P then the pseudo-randomness is generated
-** internally and without recourse to the [sqlite3_vfs] xRandomness
-** method.
-*/
-SQLITE_API void sqlite3_randomness(int N, void *P);
-
-/*
-** CAPI3REF: Compile-Time Authorization Callbacks
-** METHOD: sqlite3
-** KEYWORDS: {authorizer callback}
-**
-** ^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_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
-** and [sqlite3_prepare16_v3()]. ^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 either NULL pointers or zero-terminated strings
-** that contain additional details about the action to be authorized.
-** Applications must always be prepared to encounter a NULL pointer in any
-** of the third through the sixth parameters of the authorization callback.
-**
-** ^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.
-** ^When a table is referenced by a [SELECT] but no column values are
-** extracted from that table (for example in a query like
-** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
-** is invoked once for that table with a column name that is an empty string.
-** ^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 [conflict resolution mode]
-** returned 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 */
-
-/*
-** 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 */
-#define SQLITE_RECURSIVE 33 /* NULL NULL */
-
-/*
-** CAPI3REF: Tracing And Profiling Functions
-** METHOD: sqlite3
-**
-** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
-** instead of the routines described here.
-**
-** 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 [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
-** the length of [bound parameter] expansion in the output of sqlite3_trace().
-**
-** ^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. Invoking
-** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
-** profile callback.
-*/
-SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
- void(*xTrace)(void*,const char*), void*);
-SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
- void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
-
-/*
-** CAPI3REF: SQL Trace Event Codes
-** KEYWORDS: SQLITE_TRACE
-**
-** These constants identify classes of events that can be monitored
-** using the [sqlite3_trace_v2()] tracing logic. The M argument
-** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
-** the following constants. ^The first argument to the trace callback
-** is one of the following constants.
-**
-** New tracing constants may be added in future releases.
-**
-** ^A trace callback has four arguments: xCallback(T,C,P,X).
-** ^The T argument is one of the integer type codes above.
-** ^The C argument is a copy of the context pointer passed in as the
-** fourth argument to [sqlite3_trace_v2()].
-** The P and X arguments are pointers whose meanings depend on T.
-**
-**
-** [[SQLITE_TRACE_STMT]] - SQLITE_TRACE_STMT
-** - ^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
-** first begins running and possibly at other times during the
-** execution of the prepared statement, such as at the start of each
-** trigger subprogram. ^The P argument is a pointer to the
-** [prepared statement]. ^The X argument is a pointer to a string which
-** is the unexpanded SQL text of the prepared statement or an SQL comment
-** that indicates the invocation of a trigger. ^The callback can compute
-** the same text that would have been returned by the legacy [sqlite3_trace()]
-** interface by using the X argument when X begins with "--" and invoking
-** [sqlite3_expanded_sql(P)] otherwise.
-**
-** [[SQLITE_TRACE_PROFILE]]
- SQLITE_TRACE_PROFILE
-** - ^An SQLITE_TRACE_PROFILE callback provides approximately the same
-** information as is provided by the [sqlite3_profile()] callback.
-** ^The P argument is a pointer to the [prepared statement] and the
-** X argument points to a 64-bit integer which is the estimated of
-** the number of nanosecond that the prepared statement took to run.
-** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
-**
-** [[SQLITE_TRACE_ROW]]
- SQLITE_TRACE_ROW
-** - ^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
-** statement generates a single row of result.
-** ^The P argument is a pointer to the [prepared statement] and the
-** X argument is unused.
-**
-** [[SQLITE_TRACE_CLOSE]]
- SQLITE_TRACE_CLOSE
-** - ^An SQLITE_TRACE_CLOSE callback is invoked when a database
-** connection closes.
-** ^The P argument is a pointer to the [database connection] object
-** and the X argument is unused.
-**
-*/
-#define SQLITE_TRACE_STMT 0x01
-#define SQLITE_TRACE_PROFILE 0x02
-#define SQLITE_TRACE_ROW 0x04
-#define SQLITE_TRACE_CLOSE 0x08
-
-/*
-** CAPI3REF: SQL Trace Hook
-** METHOD: sqlite3
-**
-** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
-** function X against [database connection] D, using property mask M
-** and context pointer P. ^If the X callback is
-** NULL or if the M mask is zero, then tracing is disabled. The
-** M argument should be the bitwise OR-ed combination of
-** zero or more [SQLITE_TRACE] constants.
-**
-** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
-** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
-**
-** ^The X callback is invoked whenever any of the events identified by
-** mask M occur. ^The integer return value from the callback is currently
-** ignored, though this may change in future releases. Callback
-** implementations should return zero to ensure future compatibility.
-**
-** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
-** ^The T argument is one of the [SQLITE_TRACE]
-** constants to indicate why the callback was invoked.
-** ^The C argument is a copy of the context pointer.
-** The P and X arguments are pointers whose meanings depend on T.
-**
-** The sqlite3_trace_v2() interface is intended to replace the legacy
-** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
-** are deprecated.
-*/
-SQLITE_API int sqlite3_trace_v2(
- sqlite3*,
- unsigned uMask,
- int(*xCallback)(unsigned,void*,void*,void*),
- void *pCtx
-);
-
-/*
-** CAPI3REF: Query Progress Callbacks
-** METHOD: sqlite3
-**
-** ^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 approximate number of
-** [virtual machine instructions] that are evaluated between successive
-** invocations of the callback X. ^If N is less than one then the progress
-** handler is disabled.
-**
-** ^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
-** CONSTRUCTOR: sqlite3
-**
-** ^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 will be UTF-8 for databases created using
-** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
-** created using sqlite3_open16() will be UTF-16 in the native byte order.
-**
-** 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 third 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.
-** 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 and its built-in [VFSes] interpret the
-** following 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",
-** "rwc", or "memory". 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_open_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 the mode option is
-** set to "memory" then a pure [in-memory database] that never reads
-** or writes from disk 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 in the third parameter to sqlite3_open_v2().
-**
-**
- 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 behavior requested by setting
-** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
-**
-**
- psow: ^The psow parameter indicates whether or not the
-** [powersafe overwrite] property does or does not apply to the
-** storage media on which the database file resides.
-**
-**
- nolock: ^The nolock parameter is a boolean query parameter
-** which if set disables file locking in rollback journal modes. This
-** is useful for accessing a database on a filesystem that does not
-** support locking. Caution: Database corruption might result if two
-** or more processes write to the same database and any one of those
-** processes uses nolock=1.
-**
-**
- immutable: ^The immutable parameter is a boolean query
-** parameter that indicates that the database file is stored on
-** read-only media. ^When immutable is set, SQLite assumes that the
-** database file cannot be changed, even by a process with higher
-** privilege, and so the database is opened read-only and all locking
-** and change detection is disabled. Caution: Setting the immutable
-** property on a database file that does in fact change can result
-** in incorrect query results and/or [SQLITE_CORRUPT] errors.
-** See also: [SQLITE_IOCAP_IMMUTABLE].
-**
-**
-**
-** ^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-dotfile |
-** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
-** that uses dot-files in place of posix advisory locking.
-** |
| 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().
-**
-** Note to Windows Runtime users: The temporary directory must be set
-** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
-** features that require the use of temporary files may fail.
-**
-** See also: [sqlite3_temp_directory]
-*/
-SQLITE_API int sqlite3_open(
- const char *filename, /* Database filename (UTF-8) */
- sqlite3 **ppDb /* OUT: SQLite db handle */
-);
-SQLITE_API int sqlite3_open16(
- const void *filename, /* Database filename (UTF-16) */
- sqlite3 **ppDb /* OUT: SQLite db handle */
-);
-SQLITE_API int sqlite3_open_v2(
- const char *filename, /* Database filename (UTF-8) */
- sqlite3 **ppDb, /* OUT: SQLite db handle */
- int flags, /* Flags */
- const char *zVfs /* Name of VFS module to use */
-);
-
-/*
-** CAPI3REF: Obtain Values For URI Parameters
-**
-** These are utility routines, useful to VFS implementations, that check
-** to see if a database file was a URI that contained a specific query
-** parameter, and if so obtains the value of that query parameter.
-**
-** If F is the database filename pointer passed into the xOpen() method of
-** a VFS implementation when the flags parameter to xOpen() has one or
-** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
-** P is the name of the query parameter, then
-** sqlite3_uri_parameter(F,P) returns the value of the P
-** parameter if it exists or a NULL pointer if P does not appear as a
-** query parameter on F. If P is a query parameter of F
-** has no explicit value, then sqlite3_uri_parameter(F,P) returns
-** a pointer to an empty string.
-**
-** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
-** parameter and returns true (1) or false (0) according to the value
-** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
-** value of query parameter P is one of "yes", "true", or "on" in any
-** case or if the value begins with a non-zero number. The
-** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
-** query parameter P is one of "no", "false", or "off" in any case or
-** if the value begins with a numeric zero. If P is not a query
-** parameter on F or if the value of P is does not match any of the
-** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
-**
-** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
-** 64-bit signed integer and returns that integer, or D if P does not
-** exist. If the value of P is something other than an integer, then
-** zero is returned.
-**
-** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
-** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
-** is not a database file pathname pointer that SQLite passed into the xOpen
-** VFS method, then the behavior of this routine is undefined and probably
-** undesirable.
-**
-** See the [URI filename] documentation for additional information.
-*/
-SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
-SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
-SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
-
-
-/*
-** CAPI3REF: Error Codes And Messages
-** METHOD: sqlite3
-**
-** ^If the most recent sqlite3_* API call associated with
-** [database connection] D failed, then the sqlite3_errcode(D) interface
-** returns the numeric [result code] or [extended result code] for that
-** API call.
-** ^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 values returned by sqlite3_errcode() and/or
-** sqlite3_extended_errcode() might change with each API call.
-** Except, there are some interfaces that are guaranteed to never
-** change the value of the error code. The error-code preserving
-** interfaces are:
-**
-**
-** - sqlite3_errcode()
-**
- sqlite3_extended_errcode()
-**
- sqlite3_errmsg()
-**
- sqlite3_errmsg16()
-**
-**
-** ^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.)^
-**
-** ^The sqlite3_errstr() interface returns the English-language text
-** that describes the [result code], as UTF-8.
-** ^(Memory to hold the error message string is managed internally
-** and must not be freed by the application)^.
-**
-** 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 const char *sqlite3_errmsg(sqlite3*);
-SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
-SQLITE_API const char *sqlite3_errstr(int);
-
-/*
-** CAPI3REF: Prepared Statement Object
-** KEYWORDS: {prepared statement} {prepared statements}
-**
-** An instance of this object represents a single SQL statement that
-** has been compiled into binary form and is ready to be evaluated.
-**
-** Think of each SQL statement as a separate computer program. The
-** original SQL text is source code. A prepared statement object
-** is the compiled object code. All SQL must be converted into a
-** prepared statement before it can be run.
-**
-** The life-cycle of a prepared statement object usually goes like this:
-**
-**
-** - Create the prepared statement object using [sqlite3_prepare_v2()].
-**
- Bind values to [parameters] using the sqlite3_bind_*()
-** interfaces.
-**
- Run the SQL by calling [sqlite3_step()] one or more times.
-**
- Reset the prepared statement using [sqlite3_reset()] then go back
-** to step 2. Do this zero or more times.
-**
- Destroy the object using [sqlite3_finalize()].
-**
-*/
-typedef struct sqlite3_stmt sqlite3_stmt;
-
-/*
-** CAPI3REF: Run-time Limits
-** METHOD: sqlite3
-**
-** ^(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. If [sqlite3_prepare_v2()] or
-** the equivalent tries to allocate space for more than this many opcodes
-** in a single prepared statement, an SQLITE_NOMEM error is returned.
)^
-**
-** [[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.
)^
-**
-** [[SQLITE_LIMIT_WORKER_THREADS]] ^(- SQLITE_LIMIT_WORKER_THREADS
-** - The maximum number of auxiliary worker threads that a single
-** [prepared statement] may start.
)^
-**
-*/
-#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
-#define SQLITE_LIMIT_WORKER_THREADS 11
-
-/*
-** CAPI3REF: Prepare Flags
-**
-** These constants define various flags that can be passed into
-** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
-** [sqlite3_prepare16_v3()] interfaces.
-**
-** New flags may be added in future releases of SQLite.
-**
-**
-** [[SQLITE_PREPARE_PERSISTENT]] ^(- SQLITE_PREPARE_PERSISTENT
-** - The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
-** that the prepared statement will be retained for a long time and
-** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
-** and [sqlite3_prepare16_v3()] assume that the prepared statement will
-** be used just once or at most a few times and then destroyed using
-** [sqlite3_finalize()] relatively soon. The current implementation acts
-** on this hint by avoiding the use of [lookaside memory] so as not to
-** deplete the limited store of lookaside memory. Future versions of
-** SQLite may act on this hint differently.
-**
-** [[SQLITE_PREPARE_NORMALIZE]]
- SQLITE_PREPARE_NORMALIZE
-** - The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
-** to be required for any prepared statement that wanted to use the
-** [sqlite3_normalized_sql()] interface. However, the
-** [sqlite3_normalized_sql()] interface is now available to all
-** prepared statements, regardless of whether or not they use this
-** flag.
-**
-** [[SQLITE_PREPARE_NO_VTAB]]
- SQLITE_PREPARE_NO_VTAB
-** - The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
-** to return an error (error code SQLITE_ERROR) if the statement uses
-** any virtual tables.
-**
-*/
-#define SQLITE_PREPARE_PERSISTENT 0x01
-#define SQLITE_PREPARE_NORMALIZE 0x02
-#define SQLITE_PREPARE_NO_VTAB 0x04
-
-/*
-** CAPI3REF: Compiling An SQL Statement
-** KEYWORDS: {SQL statement compiler}
-** METHOD: sqlite3
-** CONSTRUCTOR: sqlite3_stmt
-**
-** To execute an SQL statement, it must first be compiled into a byte-code
-** program using one of these routines. Or, in other words, these routines
-** are constructors for the [prepared statement] object.
-**
-** The preferred routine to use is [sqlite3_prepare_v2()]. The
-** [sqlite3_prepare()] interface is legacy and should be avoided.
-** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
-** for special purposes.
-**
-** The use of the UTF-8 interfaces is preferred, as SQLite currently
-** does all parsing using UTF-8. The UTF-16 interfaces are provided
-** as a convenience. The UTF-16 interfaces work by converting the
-** input text into UTF-8, then invoking the corresponding UTF-8 interface.
-**
-** 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(), sqlite3_prepare_v2(),
-** and sqlite3_prepare_v3()
-** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
-** and sqlite3_prepare16_v3() use UTF-16.
-**
-** ^If the nByte argument is negative, then zSql is read up to the
-** first zero terminator. ^If nByte is positive, then it is the
-** number of bytes read from zSql. ^If nByte is zero, then no prepared
-** statement is generated.
-** If the caller knows that the supplied string is nul-terminated, then
-** there is a small performance advantage to passing an nByte parameter that
-** is the number of bytes in the input string including
-** the nul-terminator.
-**
-** ^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(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
-** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
-** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
-** are retained for backwards compatibility, but their use is discouraged.
-** ^In the "vX" 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:
-**
-**
-** -
-** ^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. As many as [SQLITE_MAX_SCHEMA_RETRY]
-** retries will occur before sqlite3_step() gives up and returns an error.
-**
-**
-** -
-** ^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.
-**
-**
-** -
-** ^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_STAT3] compile-time option is enabled.
-**
-**
-**
-** ^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
-** the extra prepFlags parameter, which is a bit array consisting of zero or
-** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
-** sqlite3_prepare_v2() interface works exactly the same as
-** sqlite3_prepare_v3() with a zero prepFlags parameter.
-*/
-SQLITE_API int sqlite3_prepare(
- sqlite3 *db, /* Database handle */
- const char *zSql, /* SQL statement, UTF-8 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const char **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare_v2(
- sqlite3 *db, /* Database handle */
- const char *zSql, /* SQL statement, UTF-8 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const char **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare_v3(
- sqlite3 *db, /* Database handle */
- const char *zSql, /* SQL statement, UTF-8 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const char **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16(
- sqlite3 *db, /* Database handle */
- const void *zSql, /* SQL statement, UTF-16 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const void **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16_v2(
- sqlite3 *db, /* Database handle */
- const void *zSql, /* SQL statement, UTF-16 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const void **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-SQLITE_API int sqlite3_prepare16_v3(
- sqlite3 *db, /* Database handle */
- const void *zSql, /* SQL statement, UTF-16 encoded */
- int nByte, /* Maximum length of zSql in bytes. */
- unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
- sqlite3_stmt **ppStmt, /* OUT: Statement handle */
- const void **pzTail /* OUT: Pointer to unused portion of zSql */
-);
-
-/*
-** CAPI3REF: Retrieving Statement SQL
-** METHOD: sqlite3_stmt
-**
-** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
-** SQL text used to create [prepared statement] P if P was
-** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
-** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
-** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
-** string containing the SQL text of prepared statement P with
-** [bound parameters] expanded.
-** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
-** string containing the normalized SQL text of prepared statement P. The
-** semantics used to normalize a SQL statement are unspecified and subject
-** to change. At a minimum, literal values will be replaced with suitable
-** placeholders.
-**
-** ^(For example, if a prepared statement is created using the SQL
-** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
-** and parameter :xyz is unbound, then sqlite3_sql() will return
-** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
-** will return "SELECT 2345,NULL".)^
-**
-** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
-** is available to hold the result, or if the result would exceed the
-** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
-**
-** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
-** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
-** option causes sqlite3_expanded_sql() to always return NULL.
-**
-** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
-** are managed by SQLite and are automatically freed when the prepared
-** statement is finalized.
-** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
-** is obtained from [sqlite3_malloc()] and must be free by the application
-** by passing it to [sqlite3_free()].
-*/
-SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
-SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
-SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Determine If An SQL Statement Writes The Database
-** METHOD: sqlite3_stmt
-**
-** ^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.
-** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
-** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
-** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
-** sqlite3_stmt_readonly() returns false for those commands.
-*/
-SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
-** METHOD: sqlite3_stmt
-**
-** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
-** prepared statement S is an EXPLAIN statement, or 2 if the
-** statement S is an EXPLAIN QUERY PLAN.
-** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
-** an ordinary statement or a NULL pointer.
-*/
-SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Determine If A Prepared Statement Has Been Reset
-** METHOD: sqlite3_stmt
-**
-** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
-** [prepared statement] S has been stepped at least once using
-** [sqlite3_step(S)] but has neither run to completion (returned
-** [SQLITE_DONE] from [sqlite3_step(S)]) nor
-** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
-** interface returns false if S is a NULL pointer. If S is not a
-** NULL pointer and is not a pointer to a valid [prepared statement]
-** object, then the behavior is undefined and probably undesirable.
-**
-** This interface can be used in combination [sqlite3_next_stmt()]
-** to locate all prepared statements associated with a database
-** connection that are in need of being reset. This can be used,
-** for example, in diagnostic routines to search for prepared
-** statements that are holding a transaction open.
-*/
-SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
-
-/*
-** 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
-** [sqlite3_value_dup()] interface can be used to construct a new
-** protected sqlite3_value from an unprotected 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 as arguments
-** to [sqlite3_result_value()], [sqlite3_bind_value()], and
-** [sqlite3_value_dup()].
-** The [sqlite3_value_blob | sqlite3_value_type()] family of
-** interfaces require protected sqlite3_value objects.
-*/
-typedef struct sqlite3_value 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}
-** METHOD: sqlite3_stmt
-**
-** ^(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.
-** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
-** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
-** is ignored and the end result is the same as sqlite3_bind_null().
-**
-** ^(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 to sqlite3_bind_text() or sqlite3_bind_text16()
-** is negative, then the length of the string is
-** the number of bytes up to the first zero terminator.
-** If the fourth parameter to sqlite3_bind_blob() is negative, then
-** the behavior is undefined.
-** If a non-negative fourth parameter is provided to sqlite3_bind_text()
-** or sqlite3_bind_text16() or sqlite3_bind_text64() then
-** that parameter must be the byte offset
-** where the NUL terminator would occur assuming the string were NUL
-** terminated. If any NUL characters occur at byte offsets less than
-** the value of the fourth parameter then the resulting string value will
-** contain embedded NULs. The result of expressions involving strings
-** with embedded NULs is undefined.
-**
-** ^The fifth argument to the BLOB and string binding interfaces
-** 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 the bind API fails,
-** except the destructor is not called if the third parameter is a NULL
-** pointer or the fourth parameter is negative.
-** ^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 sixth argument to sqlite3_bind_text64() must be one of
-** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
-** to specify the encoding of the text in the third parameter. If
-** the sixth argument to sqlite3_bind_text64() is not one of the
-** allowed values shown above, or if the text encoding is different
-** from the encoding specified by the sixth parameter, then the behavior
-** is undefined.
-**
-** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
-** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
-** (just an integer to hold its size) while it is being processed.
-** Zeroblobs are intended to serve as placeholders for BLOBs whose
-** content is later written using
-** [sqlite3_blob_open | incremental BLOB I/O] routines.
-** ^A negative value for the zeroblob results in a zero-length BLOB.
-**
-** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
-** [prepared statement] S to have an SQL value of NULL, but to also be
-** associated with the pointer P of type T. ^D is either a NULL pointer or
-** a pointer to a destructor function for P. ^SQLite will invoke the
-** destructor D with a single argument of P when it is finished using
-** P. The T parameter should be a static string, preferably a string
-** literal. The sqlite3_bind_pointer() routine is part of the
-** [pointer passing interface] added for SQLite 3.20.0.
-**
-** ^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_TOOBIG] might be returned if the size of a string or BLOB
-** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
-** [SQLITE_MAX_LENGTH].
-** ^[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_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
- 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,void(*)(void*));
-SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
-SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
- void(*)(void*), unsigned char encoding);
-SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
-SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
-SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
-SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
-
-/*
-** CAPI3REF: Number Of SQL Parameters
-** METHOD: sqlite3_stmt
-**
-** ^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
-** METHOD: sqlite3_stmt
-**
-** ^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()],
-** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
-**
-** See also: [sqlite3_bind_blob|sqlite3_bind()],
-** [sqlite3_bind_parameter_count()], and
-** [sqlite3_bind_parameter_index()].
-*/
-SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
-
-/*
-** CAPI3REF: Index Of A Parameter With A Given Name
-** METHOD: sqlite3_stmt
-**
-** ^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()] or
-** [sqlite3_prepare16_v3()].
-**
-** See also: [sqlite3_bind_blob|sqlite3_bind()],
-** [sqlite3_bind_parameter_count()], and
-** [sqlite3_bind_parameter_name()].
-*/
-SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
-
-/*
-** CAPI3REF: Reset All Bindings On A Prepared Statement
-** METHOD: sqlite3_stmt
-**
-** ^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
-** METHOD: sqlite3_stmt
-**
-** ^Return the number of columns in the result set returned by the
-** [prepared statement]. ^If this routine returns 0, that means the
-** [prepared statement] returns no data (for example an [UPDATE]).
-** ^However, just because this routine returns a positive number does not
-** mean that one or more rows of data will be returned. ^A SELECT statement
-** will always have a positive sqlite3_column_count() but depending on the
-** WHERE clause constraints and the table content, it might return no rows.
-**
-** See also: [sqlite3_data_count()]
-*/
-SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
-
-/*
-** CAPI3REF: Column Names In A Result Set
-** METHOD: sqlite3_stmt
-**
-** ^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 const char *sqlite3_column_name(sqlite3_stmt*, int N);
-SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
-
-/*
-** CAPI3REF: Source Of Data In A Query Result
-** METHOD: sqlite3_stmt
-**
-** ^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 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
-SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
-SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
-
-/*
-** CAPI3REF: Declared Datatype Of A Query Result
-** METHOD: sqlite3_stmt
-**
-** ^(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 const char *sqlite3_column_decltype(sqlite3_stmt*,int);
-SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
-
-/*
-** CAPI3REF: Evaluate An SQL Statement
-** METHOD: sqlite3_stmt
-**
-** After a [prepared statement] has been prepared using any of
-** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
-** or [sqlite3_prepare16_v3()] 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 "vX" interfaces
-** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
-** [sqlite3_prepare16_v2()] or the older legacy
-** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
-** new "vX" 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] ([dateof: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 [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
-** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] 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 "vX" interfaces is recommended.
-*/
-SQLITE_API int sqlite3_step(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Number of columns in a result set
-** METHOD: sqlite3_stmt
-**
-** ^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.
-** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
-** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
-** will return non-zero if previous call to [sqlite3_step](P) returned
-** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
-** where it always returns zero since each step of that multi-step
-** pragma returns 0 columns of data.
-**
-** 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
-#ifdef SQLITE_TEXT
-# undef SQLITE_TEXT
-#else
-# define SQLITE_TEXT 3
-#endif
-#define SQLITE3_TEXT 3
-
-/*
-** CAPI3REF: Result Values From A Query
-** KEYWORDS: {column access functions}
-** METHOD: sqlite3_stmt
-**
-** Summary:
-**
-** | sqlite3_column_blob | → | BLOB result
-** |
| sqlite3_column_double | → | REAL result
-** |
| sqlite3_column_int | → | 32-bit INTEGER result
-** |
| sqlite3_column_int64 | → | 64-bit INTEGER result
-** |
| sqlite3_column_text | → | UTF-8 TEXT result
-** |
| sqlite3_column_text16 | → | UTF-16 TEXT result
-** |
| sqlite3_column_value | → | The result as an
-** [sqlite3_value|unprotected sqlite3_value] object.
-** |
| | |
-** |
| sqlite3_column_bytes | → | Size of a BLOB
-** or a UTF-8 TEXT result in bytes
-** |
| sqlite3_column_bytes16
-** | → | Size of UTF-16
-** TEXT in bytes
-** |
| sqlite3_column_type | → | Default
-** datatype of the result
-** |
-**
-** Details:
-**
-** ^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 first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
-** each return the value of a result column in a specific data format. If
-** the result column is not initially in the requested format (for example,
-** if the query returns an integer but the sqlite3_column_text() interface
-** is used to extract the value) then an automatic type conversion is performed.
-**
-** ^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 return value of sqlite3_column_type() can be used to decide which
-** of the first six interface should be used to extract the column value.
-** The value returned by sqlite3_column_type() is only meaningful if no
-** automatic type conversions have occurred for the value in question.
-** After a type conversion, the result of calling sqlite3_column_type()
-** is undefined, though harmless. Future
-** versions of SQLite may change the behavior of sqlite3_column_type()
-** following a type conversion.
-**
-** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
-** or sqlite3_column_bytes16() interfaces can be used to determine the size
-** of that BLOB or string.
-**
-** ^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.
-**
-** Warning: ^The object returned by [sqlite3_column_value()] is an
-** [unprotected sqlite3_value] object. In a multithreaded environment,
-** an unprotected sqlite3_value object may only be used safely 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()], the behavior is not threadsafe.
-** Hence, the sqlite3_column_value() interface
-** is normally only useful within the implementation of
-** [application-defined SQL functions] or [virtual tables], not within
-** top-level application code.
-**
-** The these routines may attempt to convert the datatype of the result.
-** ^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 a NULL pointer
-** |
| NULL | BLOB | Result is a NULL pointer
-** |
| INTEGER | FLOAT | Convert from integer to float
-** |
| INTEGER | TEXT | ASCII rendering of the integer
-** |
| INTEGER | BLOB | Same as INTEGER->TEXT
-** |
| FLOAT | INTEGER | [CAST] to INTEGER
-** |
| FLOAT | TEXT | ASCII rendering of the float
-** |
| FLOAT | BLOB | [CAST] to BLOB
-** |
| TEXT | INTEGER | [CAST] to INTEGER
-** |
| TEXT | FLOAT | [CAST] to REAL
-** |
| TEXT | BLOB | No change
-** |
| BLOB | INTEGER | [CAST] to INTEGER
-** |
| BLOB | FLOAT | [CAST] to REAL
-** |
| BLOB | TEXT | Add a zero terminator if needed
-** |
-**
)^
-**
-** 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 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
-** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
-** [sqlite3_free()].
-**
-** As long as the input parameters are correct, these routines will only
-** fail if an out-of-memory error occurs during a format conversion.
-** Only the following subset of interfaces are subject to out-of-memory
-** errors:
-**
-**
-** - sqlite3_column_blob()
-**
- sqlite3_column_text()
-**
- sqlite3_column_text16()
-**
- sqlite3_column_bytes()
-**
- sqlite3_column_bytes16()
-**
-**
-** If an out-of-memory error occurs, then the return value from these
-** routines is the same as if the column had contained an SQL NULL value.
-** Valid SQL NULL returns can be distinguished from out-of-memory errors
-** by invoking the [sqlite3_errcode()] immediately after the suspect
-** return value is obtained and before any
-** other SQLite interface is called on the same [database connection].
-*/
-SQLITE_API const void *sqlite3_column_blob(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 sqlite3_value *sqlite3_column_value(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 int sqlite3_column_type(sqlite3_stmt*, int iCol);
-
-/*
-** CAPI3REF: Destroy A Prepared Statement Object
-** DESTRUCTOR: sqlite3_stmt
-**
-** ^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
-** METHOD: sqlite3_stmt
-**
-** 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}
-** METHOD: sqlite3
-**
-** ^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
-** the three "sqlite3_create_function*" 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. Function sqlite3_create_window_function()
-** is similar, but allows the user to supply the extra callback functions
-** needed by [aggregate window functions].
-**
-** ^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. The application should set this parameter to
-** [SQLITE_UTF16LE] if the function implementation invokes
-** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
-** implementation invokes [sqlite3_value_text16be()] on an input, or
-** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
-** otherwise. ^The same SQL function may be registered multiple times using
-** different preferred text encodings, with different implementations for
-** each encoding.
-** ^When multiple implementations of the same function are available, SQLite
-** will pick the one that involves the least amount of data conversion.
-**
-** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
-** to signal that the function will always return the same result given
-** the same inputs within a single SQL statement. Most SQL functions are
-** deterministic. The built-in [random()] SQL function is an example of a
-** function that is not deterministic. The SQLite query planner is able to
-** perform additional optimizations on deterministic functions, so use
-** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
-**
-** ^(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 passed to the three
-** "sqlite3_create_function*" functions, 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.
-**
-** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
-** and xInverse) passed to sqlite3_create_window_function are pointers to
-** C-language callbacks that implement the new function. xStep and xFinal
-** must both be non-NULL. xValue and xInverse may either both be NULL, in
-** which case a regular aggregate function is created, or must both be
-** non-NULL, in which case the new function may be used as either an aggregate
-** or aggregate window function. More details regarding the implementation
-** of aggregate window functions are
-** [user-defined window functions|available here].
-**
-** ^(If the final parameter to sqlite3_create_function_v2() or
-** sqlite3_create_window_function() 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 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,
- const char *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*)
-);
-SQLITE_API int sqlite3_create_function16(
- sqlite3 *db,
- const void *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*)
-);
-SQLITE_API int sqlite3_create_function_v2(
- sqlite3 *db,
- const char *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*),
- void(*xDestroy)(void*)
-);
-SQLITE_API int sqlite3_create_window_function(
- sqlite3 *db,
- const char *zFunctionName,
- int nArg,
- int eTextRep,
- void *pApp,
- void (*xStep)(sqlite3_context*,int,sqlite3_value**),
- void (*xFinal)(sqlite3_context*),
- void (*xValue)(sqlite3_context*),
- void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
- void(*xDestroy)(void*)
-);
-
-/*
-** CAPI3REF: Text Encodings
-**
-** These constant define integer codes that represent the various
-** text encodings supported by SQLite.
-*/
-#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
-#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
-#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
-#define SQLITE_UTF16 4 /* Use native byte order */
-#define SQLITE_ANY 5 /* Deprecated */
-#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
-
-/*
-** CAPI3REF: Function Flags
-**
-** These constants may be ORed together with the
-** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
-** to [sqlite3_create_function()], [sqlite3_create_function16()], or
-** [sqlite3_create_function_v2()].
-*/
-#define SQLITE_DETERMINISTIC 0x800
-
-/*
-** 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 encourage programmers to avoid
-** these functions, we will not explain what they do.
-*/
-#ifndef 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 Values
-** METHOD: sqlite3_value
-**
-** Summary:
-**
-** | sqlite3_value_blob | → | BLOB value
-** |
| sqlite3_value_double | → | REAL value
-** |
| sqlite3_value_int | → | 32-bit INTEGER value
-** |
| sqlite3_value_int64 | → | 64-bit INTEGER value
-** |
| sqlite3_value_pointer | → | Pointer value
-** |
| sqlite3_value_text | → | UTF-8 TEXT value
-** |
| sqlite3_value_text16 | → | UTF-16 TEXT value in
-** the native byteorder
-** |
| sqlite3_value_text16be | → | UTF-16be TEXT value
-** |
| sqlite3_value_text16le | → | UTF-16le TEXT value
-** |
| | |
-** |
| sqlite3_value_bytes | → | Size of a BLOB
-** or a UTF-8 TEXT in bytes
-** |
| sqlite3_value_bytes16
-** | → | Size of UTF-16
-** TEXT in bytes
-** |
| sqlite3_value_type | → | Default
-** datatype of the value
-** |
| sqlite3_value_numeric_type
-** | → | Best numeric datatype of the value
-** |
| sqlite3_value_nochange
-** | → | True if the column is unchanged in an UPDATE
-** against a virtual table.
-** |
| sqlite3_value_frombind
-** | → | True if value originated from a [bound parameter]
-** |
-**
-** Details:
-**
-** These routines extract type, size, and content information from
-** [protected sqlite3_value] objects. Protected sqlite3_value objects
-** are used to pass parameter information into implementation of
-** [application-defined SQL functions] and [virtual tables].
-**
-** These routines work only with [protected sqlite3_value] objects.
-** Any attempt to use these routines on an [unprotected sqlite3_value]
-** is not threadsafe.
-**
-** ^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.
-**
-** ^If [sqlite3_value] object V was initialized
-** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
-** and if X and Y are strings that compare equal according to strcmp(X,Y),
-** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
-** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
-** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
-**
-** ^(The sqlite3_value_type(V) interface returns the
-** [SQLITE_INTEGER | datatype code] for the initial datatype of the
-** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
-** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
-** Other interfaces might change the datatype for an sqlite3_value object.
-** For example, if the datatype is initially SQLITE_INTEGER and
-** sqlite3_value_text(V) is called to extract a text value for that
-** integer, then subsequent calls to sqlite3_value_type(V) might return
-** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
-** occurs is undefined and may change from one release of SQLite to the next.
-**
-** ^(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.)^
-**
-** ^Within the [xUpdate] method of a [virtual table], the
-** sqlite3_value_nochange(X) interface returns true if and only if
-** the column corresponding to X is unchanged by the UPDATE operation
-** that the xUpdate method call was invoked to implement and if
-** and the prior [xColumn] method call that was invoked to extracted
-** the value for that column returned without setting a result (probably
-** because it queried [sqlite3_vtab_nochange()] and found that the column
-** was unchanging). ^Within an [xUpdate] method, any value for which
-** sqlite3_value_nochange(X) is true will in all other respects appear
-** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
-** than within an [xUpdate] method call for an UPDATE statement, then
-** the return value is arbitrary and meaningless.
-**
-** ^The sqlite3_value_frombind(X) interface returns non-zero if the
-** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
-** interfaces. ^If X comes from an SQL literal value, or a table column,
-** and expression, then sqlite3_value_frombind(X) returns zero.
-**
-** 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.
-**
-** As long as the input parameter is correct, these routines can only
-** fail if an out-of-memory error occurs during a format conversion.
-** Only the following subset of interfaces are subject to out-of-memory
-** errors:
-**
-**
-** - sqlite3_value_blob()
-**
- sqlite3_value_text()
-**
- sqlite3_value_text16()
-**
- sqlite3_value_text16le()
-**
- sqlite3_value_text16be()
-**
- sqlite3_value_bytes()
-**
- sqlite3_value_bytes16()
-**
-**
-** If an out-of-memory error occurs, then the return value from these
-** routines is the same as if the column had contained an SQL NULL value.
-** Valid SQL NULL returns can be distinguished from out-of-memory errors
-** by invoking the [sqlite3_errcode()] immediately after the suspect
-** return value is obtained and before any
-** other SQLite interface is called on the same [database connection].
-*/
-SQLITE_API const void *sqlite3_value_blob(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 void *sqlite3_value_pointer(sqlite3_value*, const char*);
-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_bytes(sqlite3_value*);
-SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
-SQLITE_API int sqlite3_value_type(sqlite3_value*);
-SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
-SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
-SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
-
-/*
-** CAPI3REF: Finding The Subtype Of SQL Values
-** METHOD: sqlite3_value
-**
-** The sqlite3_value_subtype(V) function returns the subtype for
-** an [application-defined SQL function] argument V. The subtype
-** information can be used to pass a limited amount of context from
-** one SQL function to another. Use the [sqlite3_result_subtype()]
-** routine to set the subtype for the return value of an SQL function.
-*/
-SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
-
-/*
-** CAPI3REF: Copy And Free SQL Values
-** METHOD: sqlite3_value
-**
-** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
-** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
-** is a [protected sqlite3_value] object even if the input is not.
-** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
-** memory allocation fails.
-**
-** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
-** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
-** then sqlite3_value_free(V) is a harmless no-op.
-*/
-SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
-SQLITE_API void sqlite3_value_free(sqlite3_value*);
-
-/*
-** CAPI3REF: Obtain Aggregate Function Context
-** METHOD: sqlite3_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
-** when first called 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.)^ Within the xFinal callback, it is customary to set
-** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
-** pointless memory allocations occur.
-**
-** ^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
-** METHOD: sqlite3_context
-**
-** ^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
-** METHOD: sqlite3_context
-**
-** ^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
-** METHOD: sqlite3_context
-**
-** These functions may be used by (non-aggregate) 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. An example
-** of where this might be useful is in a regular-expression matching
-** function. The compiled version of the regular expression can be stored as
-** metadata associated with the pattern string.
-** Then as long as the pattern string remains the same,
-** the compiled regular expression can be reused on multiple
-** invocations of the same function.
-**
-** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
-** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
-** value to the application-defined function. ^N is zero for the left-most
-** function argument. ^If there is no metadata
-** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
-** returns a NULL pointer.
-**
-** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
-** argument of the application-defined function. ^Subsequent
-** calls to sqlite3_get_auxdata(C,N) return P from the most recent
-** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
-** NULL if the metadata has been discarded.
-** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
-** SQLite will invoke the destructor function X with parameter P exactly
-** once, when the metadata is discarded.
-** SQLite is free to discard the metadata at any time, including:
-** - ^(when the corresponding function parameter changes)^, or
-**
- ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
-** SQL statement)^, or
-**
- ^(when sqlite3_set_auxdata() is invoked again on the same
-** parameter)^, or
-**
- ^(during the original sqlite3_set_auxdata() call when a memory
-** allocation error occurs.)^
-**
-** Note the last bullet in particular. The destructor X in
-** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
-** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
-** should be called near the end of the function implementation and the
-** function implementation should not make any use of P after
-** sqlite3_set_auxdata() has been called.
-**
-** ^(In practice, metadata is preserved between function calls for
-** function parameters that are compile-time constants, including literal
-** values and [parameters] and expressions composed from the same.)^
-**
-** The value of the N parameter to these interfaces should be non-negative.
-** Future enhancements may make use of negative N values to define new
-** kinds of function caching behavior.
-**
-** 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*, void (*)(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.
-*/
-typedef void (*sqlite3_destructor_type)(void*);
-#define SQLITE_STATIC ((sqlite3_destructor_type)0)
-#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
-
-/*
-** CAPI3REF: Setting The Result Of An SQL Function
-** METHOD: sqlite3_context
-**
-** 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(C,N) and sqlite3_result_zeroblob64(C,N)
-** interfaces set the result of the application-defined function to be
-** a BLOB containing all zero bytes and N bytes in size.
-**
-** ^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_error_toobig() interface causes SQLite to throw an
-** error indicating that a string or BLOB is too long to represent.
-**
-** ^The sqlite3_result_error_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.
-** ^The sqlite3_result_text64() interface sets the return value of an
-** application-defined function to be a text string in an encoding
-** specified by the fifth (and last) parameter, which must be one
-** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
-** ^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 3rd parameter is non-negative, then it
-** must be the byte offset into the string where the NUL terminator would
-** appear if the string where NUL terminated. If any NUL characters occur
-** in the string at a byte offset that is less than the value of the 3rd
-** parameter, then the resulting string will contain embedded NULs and the
-** result of expressions operating on strings with embedded NULs is undefined.
-** ^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 [sqlite3_malloc()] before it returns.
-**
-** ^The sqlite3_result_value() interface sets the result of
-** the application-defined function to be a copy of 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.
-**
-** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
-** SQL NULL value, just like [sqlite3_result_null(C)], except that it
-** also associates the host-language pointer P or type T with that
-** NULL value such that the pointer can be retrieved within an
-** [application-defined SQL function] using [sqlite3_value_pointer()].
-** ^If the D parameter is not NULL, then it is a pointer to a destructor
-** for the P parameter. ^SQLite invokes D with P as its only argument
-** when SQLite is finished with P. The T parameter should be a static
-** string and preferably a string literal. The sqlite3_result_pointer()
-** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
-**
-** 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_blob64(sqlite3_context*,const void*,
- sqlite3_uint64,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_text64(sqlite3_context*, const char*,sqlite3_uint64,
- void(*)(void*), unsigned char encoding);
-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_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
-SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
-SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
-
-
-/*
-** CAPI3REF: Setting The Subtype Of An SQL Function
-** METHOD: sqlite3_context
-**
-** The sqlite3_result_subtype(C,T) function causes the subtype of
-** the result from the [application-defined SQL function] with
-** [sqlite3_context] C to be the value T. Only the lower 8 bits
-** of the subtype T are preserved in current versions of SQLite;
-** higher order bits are discarded.
-** The number of subtype bytes preserved by SQLite might increase
-** in future releases of SQLite.
-*/
-SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
-
-/*
-** CAPI3REF: Define New Collating Sequences
-** METHOD: sqlite3
-**
-** ^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:
-**
-**
-** - If A==B then B==A.
-**
- If A==B and B==C then A==C.
-**
- If A<B THEN B>A.
-**
- 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*,
- const char *zName,
- int eTextRep,
- void *pArg,
- int(*xCompare)(void*,int,const void*,int,const void*)
-);
-SQLITE_API int sqlite3_create_collation_v2(
- sqlite3*,
- const char *zName,
- int eTextRep,
- void *pArg,
- int(*xCompare)(void*,int,const void*,int,const void*),
- void(*xDestroy)(void*)
-);
-SQLITE_API int sqlite3_create_collation16(
- sqlite3*,
- const void *zName,
- int eTextRep,
- void *pArg,
- int(*xCompare)(void*,int,const void*,int,const void*)
-);
-
-/*
-** CAPI3REF: Collation Needed Callbacks
-** METHOD: sqlite3
-**
-** ^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*)
-);
-
-#ifdef 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 */
-);
-SQLITE_API int sqlite3_key_v2(
- sqlite3 *db, /* Database to be rekeyed */
- const char *zDbName, /* Name of the database */
- 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 */
-);
-SQLITE_API int sqlite3_rekey_v2(
- sqlite3 *db, /* Database to be rekeyed */
- const char *zDbName, /* Name of the database */
- 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(
- const char *zPassPhrase /* Activation phrase */
-);
-#endif
-
-#ifdef 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(
- const char *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.
-**
-** Applications are strongly discouraged from using this global variable.
-** It is required to set a temporary folder on Windows Runtime (WinRT).
-** But for all other platforms, it is highly recommended that applications
-** neither read nor write this variable. This global variable is a relic
-** that exists for backwards compatibility of legacy applications and should
-** be avoided in new projects.
-**
-** 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.
-** Except when requested by the [temp_store_directory pragma], SQLite
-** does not free the memory that sqlite3_temp_directory points to. If
-** the application wants that memory to be freed, it must do
-** so itself, taking care to only do so after all [database connection]
-** objects have been destroyed.
-**
-** Note to Windows Runtime users: The temporary directory must be set
-** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
-** features that require the use of temporary files may fail. Here is an
-** example of how to do this using C++ with the Windows Runtime:
-**
-**
-** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
-** TemporaryFolder->Path->Data();
-** char zPathBuf[MAX_PATH + 1];
-** memset(zPathBuf, 0, sizeof(zPathBuf));
-** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
-** NULL, NULL);
-** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
-**
-*/
-SQLITE_API char *sqlite3_temp_directory;
-
-/*
-** CAPI3REF: Name Of The Folder Holding Database 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 database files
-** specified with a relative pathname and created or accessed by
-** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
-** to be relative to that directory.)^ ^If this variable is a NULL
-** pointer, then SQLite assumes that all database files specified
-** with a relative pathname are relative to the current directory
-** for the process. Only the windows VFS makes use of this global
-** variable; it is ignored by the unix VFS.
-**
-** Changing the value of this variable while a database connection is
-** open can result in a corrupt database.
-**
-** 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 [data_store_directory pragma] may modify this variable and cause
-** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
-** the [data_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 [data_store_directory pragma] should be avoided.
-*/
-SQLITE_API char *sqlite3_data_directory;
-
-/*
-** CAPI3REF: Win32 Specific Interface
-**
-** These interfaces are available only on Windows. The
-** [sqlite3_win32_set_directory] interface is used to set the value associated
-** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
-** zValue, depending on the value of the type parameter. The zValue parameter
-** should be NULL to cause the previous value to be freed via [sqlite3_free];
-** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
-** prior to being used. The [sqlite3_win32_set_directory] interface returns
-** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
-** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
-** [sqlite3_data_directory] variable is intended to act as a replacement for
-** the current directory on the sub-platforms of Win32 where that concept is
-** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
-** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
-** sqlite3_win32_set_directory interface except the string parameter must be
-** UTF-8 or UTF-16, respectively.
-*/
-SQLITE_API int sqlite3_win32_set_directory(
- unsigned long type, /* Identifier for directory being set or reset */
- void *zValue /* New value for directory being set or reset */
-);
-SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
-SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
-
-/*
-** CAPI3REF: Win32 Directory Types
-**
-** These macros are only available on Windows. They define the allowed values
-** for the type argument to the [sqlite3_win32_set_directory] interface.
-*/
-#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
-#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
-
-/*
-** CAPI3REF: Test For Auto-Commit Mode
-** KEYWORDS: {autocommit mode}
-** METHOD: sqlite3
-**
-** ^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
-** METHOD: sqlite3_stmt
-**
-** ^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: Return The Filename For A Database Connection
-** METHOD: sqlite3
-**
-** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
-** associated with database N of connection D. ^The main database file
-** has the name "main". If there is no attached database N on the database
-** connection D, or if database N is a temporary or in-memory database, then
-** this function will return either a NULL pointer or an empty string.
-**
-** ^The filename returned by this function is the output of the
-** xFullPathname method of the [VFS]. ^In other words, the filename
-** will be an absolute pathname, even if the filename used
-** to open the database originally was a URI or relative pathname.
-*/
-SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
-
-/*
-** CAPI3REF: Determine if a database is read-only
-** METHOD: sqlite3
-**
-** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
-** of connection D is read-only, 0 if it is read/write, or -1 if N is not
-** the name of a database on connection D.
-*/
-SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
-
-/*
-** CAPI3REF: Find the next prepared statement
-** METHOD: sqlite3
-**
-** ^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
-** METHOD: sqlite3
-**
-** ^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 commit and rollback hook callbacks are not reentrant.
-** 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 running any other SQL statements, including SELECT statements,
-** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
-** the 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
-** METHOD: sqlite3
-**
-** ^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 in
-** a [rowid table].
-** ^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 in a rowid table.
-** ^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).)^
-** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
-**
-** ^In the current implementation, the update hook
-** is not invoked when conflicting 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()], [sqlite3_rollback_hook()],
-** and [sqlite3_preupdate_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
-**
-** ^(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] ([dateof: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.
-**
-** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
-** and will always return SQLITE_MISUSE. On those systems,
-** shared cache mode should be enabled per-database connection via
-** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
-**
-** This interface is threadsafe on processors where writing a
-** 32-bit integer is atomic.
-**
-** 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].
-**
-** See also: [sqlite3_db_release_memory()]
-*/
-SQLITE_API int sqlite3_release_memory(int);
-
-/*
-** CAPI3REF: Free Memory Used By A Database Connection
-** METHOD: sqlite3
-**
-** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
-** memory as possible from database connection D. Unlike the
-** [sqlite3_release_memory()] interface, this interface is in effect even
-** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
-** omitted.
-**
-** See also: [sqlite3_release_memory()]
-*/
-SQLITE_API int sqlite3_db_release_memory(sqlite3*);
-
-/*
-** 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, or negative in the case of an
-** error. ^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_PCACHE2],...).
-**
- 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] ([dateof: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
-** METHOD: sqlite3
-**
-** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
-** information about column C of table T in database D
-** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
-** interface returns SQLITE_OK and fills in the non-NULL pointers in
-** the final five arguments with appropriate values if the specified
-** column exists. ^The sqlite3_table_column_metadata() interface returns
-** SQLITE_ERROR and if the specified column does not exist.
-** ^If the column-name parameter to sqlite3_table_column_metadata() is a
-** NULL pointer, then this routine simply checks for the existence of the
-** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
-** does not. If the table name parameter T in a call to
-** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
-** undefined behavior.
-**
-** ^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.
-**
-** ^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 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 the table
-** is not a [WITHOUT ROWID] table 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
-** [INTEGER PRIMARY KEY] column, then the outputs
-** for the [rowid] are set as follows:
-**
-**
-** data type: "INTEGER"
-** collation sequence: "BINARY"
-** not null: 0
-** primary key: 1
-** auto increment: 0
-**
)^
-**
-** ^This function causes all database schemas to be read from disk and
-** parsed, if that has not already been done, and returns an error if
-** any errors are encountered while loading the schema.
-*/
-SQLITE_API int sqlite3_table_column_metadata(
- sqlite3 *db, /* Connection handle */
- const char *zDbName, /* Database name or NULL */
- const char *zTableName, /* Table name */
- const char *zColumnName, /* Column name */
- char const **pzDataType, /* OUTPUT: Declared data type */
- char const **pzCollSeq, /* OUTPUT: Collation sequence name */
- int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
- int *pPrimaryKey, /* OUTPUT: True if column part of PK */
- int *pAutoinc /* OUTPUT: True if column is auto-increment */
-);
-
-/*
-** CAPI3REF: Load An Extension
-** METHOD: sqlite3
-**
-** ^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. If
-** the file cannot be loaded directly, attempts are made to load
-** with various operating-system specific extensions added.
-** So for example, if "samplelib" cannot be loaded, then names like
-** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
-** be tried also.
-**
-** ^The entry point is zProc.
-** ^(zProc may be 0, in which case SQLite will try to come up with an
-** entry point name on its own. It first tries "sqlite3_extension_init".
-** If that does not work, it constructs a name "sqlite3_X_init" where the
-** X is consists of the lower-case equivalent of all ASCII alphabetic
-** characters in the filename from the last "/" to the first following
-** "." and omitting any initial "lib".)^
-** ^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()] or
-** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
-** prior to calling this API,
-** otherwise an error will be returned.
-**
-** Security warning: It is recommended that the
-** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
-** interface. The use of the [sqlite3_enable_load_extension()] interface
-** should be avoided. This will keep the SQL function [load_extension()]
-** disabled and prevent SQL injections from giving attackers
-** access to extension loading capabilities.
-**
-** See also the [load_extension() SQL function].
-*/
-SQLITE_API int sqlite3_load_extension(
- sqlite3 *db, /* Load the extension into this database connection */
- const char *zFile, /* Name of the shared library containing extension */
- const char *zProc, /* Entry point. Derived from zFile if 0 */
- char **pzErrMsg /* Put error message here if not 0 */
-);
-
-/*
-** CAPI3REF: Enable Or Disable Extension Loading
-** METHOD: sqlite3
-**
-** ^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.
-** ^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.
-**
-** ^This interface enables or disables both the C-API
-** [sqlite3_load_extension()] and the SQL function [load_extension()].
-** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
-** to enable or disable only the C-API.)^
-**
-** Security warning: It is recommended that extension loading
-** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
-** rather than this interface, so the [load_extension()] SQL function
-** remains disabled. This will prevent SQL injections from giving attackers
-** access to extension loading capabilities.
-*/
-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 an integer result as if the signature of the
-** entry point where as follows:
-**
-**
-** int xEntryPoint(
-** sqlite3 *db,
-** const char **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()]
-** and [sqlite3_cancel_auto_extension()]
-*/
-SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
-
-/*
-** CAPI3REF: Cancel Automatic Extension Loading
-**
-** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
-** initialization routine X that was registered using a prior call to
-** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
-** routine returns 1 if initialization routine X was successfully
-** unregistered and it returns 0 if X was not on the list of initialization
-** routines.
-*/
-SQLITE_API int sqlite3_cancel_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*, void *pAux,
- int argc, const char *const*argv,
- sqlite3_vtab **ppVTab, char**);
- int (*xConnect)(sqlite3*, void *pAux,
- int argc, const char *const*argv,
- sqlite3_vtab **ppVTab, char**);
- int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
- int (*xDisconnect)(sqlite3_vtab *pVTab);
- int (*xDestroy)(sqlite3_vtab *pVTab);
- int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
- int (*xClose)(sqlite3_vtab_cursor*);
- int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
- int argc, sqlite3_value **argv);
- int (*xNext)(sqlite3_vtab_cursor*);
- int (*xEof)(sqlite3_vtab_cursor*);
- int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
- int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
- int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
- int (*xBegin)(sqlite3_vtab *pVTab);
- int (*xSync)(sqlite3_vtab *pVTab);
- int (*xCommit)(sqlite3_vtab *pVTab);
- int (*xRollback)(sqlite3_vtab *pVTab);
- int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
- void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
- void **ppArg);
- int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
- /* 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);
- /* The methods above are in versions 1 and 2 of the sqlite_module object.
- ** Those below are for version 3 and greater. */
- int (*xShadowName)(const char*);
-};
-
-/*
-** 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 colUsed field indicates which columns of the virtual table may be
-** required by the current scan. Virtual table columns are numbered from
-** zero in the order in which they appear within the CREATE TABLE statement
-** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
-** the corresponding bit is set within the colUsed mask if the column may be
-** required by SQLite. If the table has at least 64 columns and any column
-** to the right of the first 63 is required, then bit 63 of colUsed is also
-** set. In other words, column iCol may be required if the expression
-** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
-** non-zero.
-**
-** 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 a particular
-** strategy. A cost of N indicates that the cost of the strategy is similar
-** to a linear scan of an SQLite table with N rows. A cost of log(N)
-** indicates that the expense of the operation is similar to that of a
-** binary search on a unique indexed field of an SQLite table with N rows.
-**
-** ^The estimatedRows value is an estimate of the number of rows that
-** will be returned by the strategy.
-**
-** The xBestIndex method may optionally populate the idxFlags field with a
-** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
-** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
-** assumes that the strategy may visit at most one row.
-**
-** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
-** SQLite also assumes that if a call to the xUpdate() method is made as
-** part of the same statement to delete or update a virtual table row and the
-** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
-** any database changes. In other words, if the xUpdate() returns
-** SQLITE_CONSTRAINT, the database contents must be exactly as they were
-** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
-** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
-** the xUpdate method are automatically rolled back by SQLite.
-**
-** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
-** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
-** If a virtual table extension is
-** used with an SQLite version earlier than 3.8.2, the results of attempting
-** to read or write the estimatedRows field are undefined (but are likely
-** to included crashing the application). The estimatedRows field should
-** therefore only be used if [sqlite3_libversion_number()] returns a
-** value greater than or equal to 3008002. Similarly, the idxFlags field
-** was added for [version 3.9.0] ([dateof:3.9.0]).
-** It may therefore only be used if
-** sqlite3_libversion_number() returns a value greater than or equal to
-** 3009000.
-*/
-struct sqlite3_index_info {
- /* Inputs */
- int nConstraint; /* Number of entries in aConstraint */
- struct sqlite3_index_constraint {
- int iColumn; /* Column constrained. -1 for ROWID */
- 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 */
- /* Fields below are only available in SQLite 3.8.2 and later */
- sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
- /* Fields below are only available in SQLite 3.9.0 and later */
- int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
- /* Fields below are only available in SQLite 3.10.0 and later */
- sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
-};
-
-/*
-** CAPI3REF: Virtual Table Scan Flags
-**
-** Virtual table implementations are allowed to set the
-** [sqlite3_index_info].idxFlags field to some combination of
-** these bits.
-*/
-#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
-
-/*
-** 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
-#define SQLITE_INDEX_CONSTRAINT_LIKE 65
-#define SQLITE_INDEX_CONSTRAINT_GLOB 66
-#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
-#define SQLITE_INDEX_CONSTRAINT_NE 68
-#define SQLITE_INDEX_CONSTRAINT_ISNOT 69
-#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
-#define SQLITE_INDEX_CONSTRAINT_ISNULL 71
-#define SQLITE_INDEX_CONSTRAINT_IS 72
-#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
-
-/*
-** CAPI3REF: Register A Virtual Table Implementation
-** METHOD: sqlite3
-**
-** ^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 */
- const char *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 */
- const char *zName, /* Name of the module */
- const sqlite3_module *p, /* Methods for the module */
- void *pClientData, /* Client data for xCreate/xConnect */
- void(*xDestroy)(void*) /* Module destructor function */
-);
-
-/*
-** CAPI3REF: Virtual Table Instance Object
-** 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; /* Number of open cursors */
- char *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 */
-};
-
-/*
-** 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*, const char *zSQL);
-
-/*
-** CAPI3REF: Overload A Function For A Virtual Table
-** METHOD: sqlite3
-**
-** ^(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*, const char *zFuncName, int nArg);
-
-/*
-** The interface to the virtual-table mechanism defined above (back up
-** to a comment remarkably similar to this one) is currently considered
-** to be experimental. The interface might change in incompatible ways.
-** If this is a problem for you, do not use the interface at this time.
-**
-** When the virtual-table mechanism stabilizes, we will declare the
-** interface fixed, support it indefinitely, and remove this comment.
-*/
-
-/*
-** 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
-** METHOD: sqlite3
-** CONSTRUCTOR: sqlite3_blob
-**
-** ^(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;
-**
)^
-**
-** ^(Parameter zDb is not the filename that contains the database, but
-** rather the symbolic name of the database. For attached databases, this is
-** the name that appears after the AS keyword in the [ATTACH] statement.
-** For the main database file, the database name is "main". For TEMP
-** tables, the database name is "temp".)^
-**
-** ^If the flags parameter is non-zero, then the BLOB is opened for read
-** and write access. ^If the flags parameter is zero, the BLOB is opened for
-** read-only access.
-**
-** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
-** in *ppBlob. Otherwise an [error code] is returned and, unless the error
-** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
-** the API is not misused, it is always safe to call [sqlite3_blob_close()]
-** on *ppBlob after this function it returns.
-**
-** This function fails with SQLITE_ERROR if any of the following are true:
-**
-** - ^(Database zDb does not exist)^,
-**
- ^(Table zTable does not exist within database zDb)^,
-**
- ^(Table zTable is a WITHOUT ROWID table)^,
-**
- ^(Column zColumn does not exist)^,
-**
- ^(Row iRow is not present in the table)^,
-**
- ^(The specified column of row iRow contains a value that is not
-** a TEXT or BLOB value)^,
-**
- ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
-** constraint and the blob is being opened for read/write access)^,
-**
- ^([foreign key constraints | Foreign key constraints] are enabled,
-** column zColumn is part of a [child key] definition and the blob is
-** being opened for read/write access)^.
-**
-**
-** ^Unless it returns SQLITE_MISUSE, this function sets the
-** [database connection] error code and message accessible via
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
-**
-** A BLOB referenced by sqlite3_blob_open() may be read using the
-** [sqlite3_blob_read()] interface and modified by using
-** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
-** different row of the same table using the [sqlite3_blob_reopen()]
-** interface. However, the column, table, or database of a [BLOB handle]
-** cannot be changed after the [BLOB handle] is opened.
-**
-** ^(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
-** an 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 may be used to create a
-** zero-filled blob to read or write using the incremental-blob interface.
-**
-** To avoid a resource leak, every open [BLOB handle] should eventually
-** be released by a call to [sqlite3_blob_close()].
-**
-** See also: [sqlite3_blob_close()],
-** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
-** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
-*/
-SQLITE_API int sqlite3_blob_open(
- sqlite3*,
- const char *zDb,
- const char *zTable,
- const char *zColumn,
- sqlite3_int64 iRow,
- int flags,
- sqlite3_blob **ppBlob
-);
-
-/*
-** CAPI3REF: Move a BLOB Handle to a New Row
-** METHOD: sqlite3_blob
-**
-** ^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 is
-** 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 int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
-
-/*
-** CAPI3REF: Close A BLOB Handle
-** DESTRUCTOR: sqlite3_blob
-**
-** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
-** unconditionally. Even if this routine returns an error code, the
-** handle is still closed.)^
-**
-** ^If the blob handle being closed was opened for read-write access, and if
-** the database is in auto-commit mode and there are no other open read-write
-** blob handles or active write statements, the current transaction is
-** committed. ^If an error occurs while committing the transaction, an error
-** code is returned and the transaction rolled back.
-**
-** Calling this function with an argument that is not a NULL pointer or an
-** open blob handle results in undefined behaviour. ^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. ^Otherwise, if this function
-** is passed a valid open blob handle, the values returned by the
-** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
-*/
-SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
-
-/*
-** CAPI3REF: Return The Size Of An Open BLOB
-** METHOD: sqlite3_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
-** METHOD: sqlite3_blob
-**
-** ^(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 *, void *Z, int N, int iOffset);
-
-/*
-** CAPI3REF: Write Data Into A BLOB Incrementally
-** METHOD: sqlite3_blob
-**
-** ^(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.)^
-**
-** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
-** Otherwise, an [error code] or an [extended error code] is returned.)^
-** ^Unless SQLITE_MISUSE is returned, this function sets the
-** [database connection] error code and message accessible via
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
-**
-** ^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. The size of the
-** BLOB (and hence the maximum value of N+iOffset) can be determined
-** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
-** than zero [SQLITE_ERROR] is returned and no data is written.
-**
-** ^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.
-**
-** 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 *, const void *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(const char *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_PTHREADS
-**
- 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_PTHREADS and
-** SQLITE_MUTEX_W32 implementations are appropriate for use on 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. ^The sqlite3_mutex_alloc()
-** routine returns NULL if it is unable to allocate the requested
-** mutex. The argument to sqlite3_mutex_alloc() must one of these
-** integer constants:
-**
-**
-** - SQLITE_MUTEX_FAST
-**
- SQLITE_MUTEX_RECURSIVE
-**
- SQLITE_MUTEX_STATIC_MASTER
-**
- SQLITE_MUTEX_STATIC_MEM
-**
- SQLITE_MUTEX_STATIC_OPEN
-**
- SQLITE_MUTEX_STATIC_PRNG
-**
- SQLITE_MUTEX_STATIC_LRU
-**
- SQLITE_MUTEX_STATIC_PMEM
-**
- SQLITE_MUTEX_STATIC_APP1
-**
- SQLITE_MUTEX_STATIC_APP2
-**
- SQLITE_MUTEX_STATIC_APP3
-**
- SQLITE_MUTEX_STATIC_VFS1
-**
- SQLITE_MUTEX_STATIC_VFS2
-**
- SQLITE_MUTEX_STATIC_VFS3
-**
-**
-** ^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. ^Nine 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. ^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. Attempting to deallocate a static
-** mutex results in undefined behavior.
-**
-** ^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 mutex other
-** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
-**
-** ^(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.
-**
-** ^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 application 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 application
-** 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 *);
-};
-
-/*
-** CAPI3REF: Mutex Verification Routines
-**
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
-** are intended for use inside assert() statements. The SQLite core
-** never uses these routines except inside an 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 provide 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 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.
-*/
-#ifndef 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_randomness() */
-#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
-#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
-#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
-#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
-#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
-#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
-#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
-#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
-#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
-
-/*
-** CAPI3REF: Retrieve the mutex for a database connection
-** METHOD: sqlite3
-**
-** ^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
-** METHOD: sqlite3
-** KEYWORDS: {file control}
-**
-** ^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.
-**
-** A few opcodes for [sqlite3_file_control()] are handled directly
-** by the SQLite core and never invoke the
-** sqlite3_io_methods.xFileControl method.
-** ^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_JOURNAL_POINTER] works similarly except that it returns
-** the [sqlite3_file] object associated with the journal file instead of
-** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
-** a pointer to the underlying [sqlite3_vfs] object for the file.
-** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
-** from the pager.
-**
-** ^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: [file control opcodes]
-*/
-SQLITE_API int sqlite3_file_control(sqlite3*, const char *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 /* NOT USED */
-#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
-#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
-#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
-#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
-#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
-#define SQLITE_TESTCTRL_NEVER_CORRUPT 20
-#define SQLITE_TESTCTRL_VDBE_COVERAGE 21
-#define SQLITE_TESTCTRL_BYTEORDER 22
-#define SQLITE_TESTCTRL_ISINIT 23
-#define SQLITE_TESTCTRL_SORTER_MMAP 24
-#define SQLITE_TESTCTRL_IMPOSTER 25
-#define SQLITE_TESTCTRL_PARSER_COVERAGE 26
-#define SQLITE_TESTCTRL_RESULT_INTREAL 27
-#define SQLITE_TESTCTRL_LAST 27 /* Largest TESTCTRL */
-
-/*
-** CAPI3REF: SQL Keyword Checking
-**
-** These routines provide access to the set of SQL language keywords
-** recognized by SQLite. Applications can uses these routines to determine
-** whether or not a specific identifier needs to be escaped (for example,
-** by enclosing in double-quotes) so as not to confuse the parser.
-**
-** The sqlite3_keyword_count() interface returns the number of distinct
-** keywords understood by SQLite.
-**
-** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
-** makes *Z point to that keyword expressed as UTF8 and writes the number
-** of bytes in the keyword into *L. The string that *Z points to is not
-** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
-** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
-** or L are NULL or invalid pointers then calls to
-** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
-**
-** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
-** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
-** if it is and zero if not.
-**
-** The parser used by SQLite is forgiving. It is often possible to use
-** a keyword as an identifier as long as such use does not result in a
-** parsing ambiguity. For example, the statement
-** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
-** creates a new table named "BEGIN" with three columns named
-** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
-** using keywords as identifiers. Common techniques used to avoid keyword
-** name collisions include:
-**
-** - Put all identifier names inside double-quotes. This is the official
-** SQL way to escape identifier names.
-**
- Put identifier names inside [...]. This is not standard SQL,
-** but it is what SQL Server does and so lots of programmers use this
-** technique.
-**
- Begin every identifier with the letter "Z" as no SQL keywords start
-** with "Z".
-**
- Include a digit somewhere in every identifier name.
-**
-**
-** Note that the number of keywords understood by SQLite can depend on
-** compile-time options. For example, "VACUUM" is not a keyword if
-** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
-** new keywords may be added to future releases of SQLite.
-*/
-SQLITE_API int sqlite3_keyword_count(void);
-SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
-SQLITE_API int sqlite3_keyword_check(const char*,int);
-
-/*
-** CAPI3REF: Dynamic String Object
-** KEYWORDS: {dynamic string}
-**
-** An instance of the sqlite3_str object contains a dynamically-sized
-** string under construction.
-**
-** The lifecycle of an sqlite3_str object is as follows:
-**
-** - ^The sqlite3_str object is created using [sqlite3_str_new()].
-**
- ^Text is appended to the sqlite3_str object using various
-** methods, such as [sqlite3_str_appendf()].
-**
- ^The sqlite3_str object is destroyed and the string it created
-** is returned using the [sqlite3_str_finish()] interface.
-**
-*/
-typedef struct sqlite3_str sqlite3_str;
-
-/*
-** CAPI3REF: Create A New Dynamic String Object
-** CONSTRUCTOR: sqlite3_str
-**
-** ^The [sqlite3_str_new(D)] interface allocates and initializes
-** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
-** [sqlite3_str_new()] must be freed by a subsequent call to
-** [sqlite3_str_finish(X)].
-**
-** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
-** valid [sqlite3_str] object, though in the event of an out-of-memory
-** error the returned object might be a special singleton that will
-** silently reject new text, always return SQLITE_NOMEM from
-** [sqlite3_str_errcode()], always return 0 for
-** [sqlite3_str_length()], and always return NULL from
-** [sqlite3_str_finish(X)]. It is always safe to use the value
-** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
-** to any of the other [sqlite3_str] methods.
-**
-** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
-** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
-** length of the string contained in the [sqlite3_str] object will be
-** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
-** of [SQLITE_MAX_LENGTH].
-*/
-SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
-
-/*
-** CAPI3REF: Finalize A Dynamic String
-** DESTRUCTOR: sqlite3_str
-**
-** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
-** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
-** that contains the constructed string. The calling application should
-** pass the returned value to [sqlite3_free()] to avoid a memory leak.
-** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
-** errors were encountered during construction of the string. ^The
-** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
-** string in [sqlite3_str] object X is zero bytes long.
-*/
-SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
-
-/*
-** CAPI3REF: Add Content To A Dynamic String
-** METHOD: sqlite3_str
-**
-** These interfaces add content to an sqlite3_str object previously obtained
-** from [sqlite3_str_new()].
-**
-** ^The [sqlite3_str_appendf(X,F,...)] and
-** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
-** functionality of SQLite to append formatted text onto the end of
-** [sqlite3_str] object X.
-**
-** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
-** onto the end of the [sqlite3_str] object X. N must be non-negative.
-** S must contain at least N non-zero bytes of content. To append a
-** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
-** method instead.
-**
-** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
-** zero-terminated string S onto the end of [sqlite3_str] object X.
-**
-** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
-** single-byte character C onto the end of [sqlite3_str] object X.
-** ^This method can be used, for example, to add whitespace indentation.
-**
-** ^The [sqlite3_str_reset(X)] method resets the string under construction
-** inside [sqlite3_str] object X back to zero bytes in length.
-**
-** These methods do not return a result code. ^If an error occurs, that fact
-** is recorded in the [sqlite3_str] object and can be recovered by a
-** subsequent call to [sqlite3_str_errcode(X)].
-*/
-SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
-SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
-SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
-SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
-SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
-SQLITE_API void sqlite3_str_reset(sqlite3_str*);
-
-/*
-** CAPI3REF: Status Of A Dynamic String
-** METHOD: sqlite3_str
-**
-** These interfaces return the current status of an [sqlite3_str] object.
-**
-** ^If any prior errors have occurred while constructing the dynamic string
-** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
-** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
-** [SQLITE_NOMEM] following any out-of-memory error, or
-** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
-** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
-**
-** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
-** of the dynamic string under construction in [sqlite3_str] object X.
-** ^The length returned by [sqlite3_str_length(X)] does not include the
-** zero-termination byte.
-**
-** ^The [sqlite3_str_value(X)] method returns a pointer to the current
-** content of the dynamic string under construction in X. The value
-** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
-** and might be freed or altered by any subsequent method on the same
-** [sqlite3_str] object. Applications must not used the pointer returned
-** [sqlite3_str_value(X)] after any subsequent method call on the same
-** object. ^Applications may change the content of the string returned
-** by [sqlite3_str_value(X)] as long as they do not write into any bytes
-** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
-** write any byte after any subsequent sqlite3_str method call.
-*/
-SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
-SQLITE_API int sqlite3_str_length(sqlite3_str*);
-SQLITE_API char *sqlite3_str_value(sqlite3_str*);
-
-/*
-** CAPI3REF: SQLite Runtime Status
-**
-** ^These interfaces are 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() and sqlite3_status64() routines return
-** SQLITE_OK on success and a non-zero [error code] on failure.
-**
-** If either the current value or the highwater mark is too large to
-** be represented by a 32-bit integer, then the values returned by
-** sqlite3_status() are undefined.
-**
-** See also: [sqlite3_db_status()]
-*/
-SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
-SQLITE_API int sqlite3_status64(
- int op,
- sqlite3_int64 *pCurrent,
- sqlite3_int64 *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. 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
-** - No longer used.
-**
-** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(- SQLITE_STATUS_SCRATCH_OVERFLOW
-** - No longer used.
-**
-** [[SQLITE_STATUS_SCRATCH_SIZE]] - SQLITE_STATUS_SCRATCH_SIZE
-** - No longer used.
-**
-** [[SQLITE_STATUS_PARSER_STACK]] ^(- SQLITE_STATUS_PARSER_STACK
-** - The *pHighwater parameter records the deepest parser stack.
-** The *pCurrent value is undefined. The *pHighwater value 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 /* NOT USED */
-#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
-#define SQLITE_STATUS_MALLOC_SIZE 5
-#define SQLITE_STATUS_PARSER_STACK 6
-#define SQLITE_STATUS_PAGECACHE_SIZE 7
-#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
-#define SQLITE_STATUS_MALLOC_COUNT 9
-
-/*
-** CAPI3REF: Database Connection Status
-** METHOD: sqlite3
-**
-** ^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 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_CACHE_USED_SHARED]]
-** ^(
- SQLITE_DBSTATUS_CACHE_USED_SHARED
-** - This parameter is similar to DBSTATUS_CACHE_USED, except that if a
-** pager cache is shared between two or more connections the bytes of heap
-** memory used by that pager cache is divided evenly between the attached
-** connections.)^ In other words, if none of the pager caches associated
-** with the database connection are shared, this request returns the same
-** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
-** shared, the value returned by this call will be smaller than that returned
-** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
-** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
-**
-** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
- SQLITE_DBSTATUS_SCHEMA_USED
-** - This parameter returns the approximate number 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 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.
-**
-**
-** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(- SQLITE_DBSTATUS_CACHE_HIT
-** - This parameter returns the number of pager cache hits that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
-** is always 0.
-**
-**
-** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(- SQLITE_DBSTATUS_CACHE_MISS
-** - This parameter returns the number of pager cache misses that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
-** is always 0.
-**
-**
-** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(- SQLITE_DBSTATUS_CACHE_WRITE
-** - This parameter returns the number of dirty cache entries that have
-** been written to disk. Specifically, the number of pages written to the
-** wal file in wal mode databases, or the number of pages written to the
-** database file in rollback mode databases. Any pages written as part of
-** transaction rollback or database recovery operations are not included.
-** If an IO or other error occurs while writing a page to disk, the effect
-** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
-** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
-**
-**
-** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(- SQLITE_DBSTATUS_CACHE_SPILL
-** - This parameter returns the number of dirty cache entries that have
-** been written to disk in the middle of a transaction due to the page
-** cache overflowing. Transactions are more efficient if they are written
-** to disk all at once. When pages spill mid-transaction, that introduces
-** additional overhead. This parameter can be used help identify
-** inefficiencies that can be resolve by increasing the cache size.
-**
-**
-** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(- SQLITE_DBSTATUS_DEFERRED_FKS
-** - This parameter returns zero for the current value if and only if
-** all foreign key constraints (deferred or immediate) have been
-** resolved.)^ ^The highwater mark 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_CACHE_HIT 7
-#define SQLITE_DBSTATUS_CACHE_MISS 8
-#define SQLITE_DBSTATUS_CACHE_WRITE 9
-#define SQLITE_DBSTATUS_DEFERRED_FKS 10
-#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
-#define SQLITE_DBSTATUS_CACHE_SPILL 12
-#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
-
-
-/*
-** CAPI3REF: Prepared Statement Status
-** METHOD: sqlite3_stmt
-**
-** ^(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 counter]
-** to be interrogated.)^
-** ^The current value of the requested counter is returned.
-** ^If the resetFlg is true, then the counter is reset to zero after this
-** interface call returns.
-**
-** See also: [sqlite3_status()] and [sqlite3_db_status()].
-*/
-SQLITE_API 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.
-**
-** [[SQLITE_STMTSTATUS_VM_STEP]] - SQLITE_STMTSTATUS_VM_STEP
-** - ^This is the number of virtual machine operations executed
-** by the prepared statement if that number is less than or equal
-** to 2147483647. The number of virtual machine operations can be
-** used as a proxy for the total work done by the prepared statement.
-** If the number of virtual machine operations exceeds 2147483647
-** then the value returned by this statement status code is undefined.
-**
-** [[SQLITE_STMTSTATUS_REPREPARE]]
- SQLITE_STMTSTATUS_REPREPARE
-** - ^This is the number of times that the prepare statement has been
-** automatically regenerated due to schema changes or change to
-** [bound parameters] that might affect the query plan.
-**
-** [[SQLITE_STMTSTATUS_RUN]]
- SQLITE_STMTSTATUS_RUN
-** - ^This is the number of times that the prepared statement has
-** been run. A single "run" for the purposes of this counter is one
-** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
-** The counter is incremented on the first [sqlite3_step()] call of each
-** cycle.
-**
-** [[SQLITE_STMTSTATUS_MEMUSED]]
- SQLITE_STMTSTATUS_MEMUSED
-** - ^This is the approximate number of bytes of heap memory
-** used to store the prepared statement. ^This value is not actually
-** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
-** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
-**
-**
-*/
-#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
-#define SQLITE_STMTSTATUS_SORT 2
-#define SQLITE_STMTSTATUS_AUTOINDEX 3
-#define SQLITE_STMTSTATUS_VM_STEP 4
-#define SQLITE_STMTSTATUS_REPREPARE 5
-#define SQLITE_STMTSTATUS_RUN 6
-#define SQLITE_STMTSTATUS_MEMUSED 99
-
-/*
-** 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_methods2] for additional information.
-*/
-typedef struct sqlite3_pcache sqlite3_pcache;
-
-/*
-** CAPI3REF: Custom Page Cache Object
-**
-** The sqlite3_pcache_page object represents a single page in the
-** page cache. The page cache will allocate instances of this
-** object. Various methods of the page cache use pointers to instances
-** of this object as parameters or as their return value.
-**
-** See [sqlite3_pcache_methods2] for additional information.
-*/
-typedef struct sqlite3_pcache_page sqlite3_pcache_page;
-struct sqlite3_pcache_page {
- void *pBuf; /* The content of the page */
- void *pExtra; /* Extra information associated with the page */
-};
-
-/*
-** CAPI3REF: Application Defined Page Cache.
-** KEYWORDS: {page cache}
-**
-** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
-** register an alternative page cache implementation by passing in an
-** instance of the sqlite3_pcache_methods2 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_methods2 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_methods2.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 always a power of two. ^The
-** second parameter szExtra is a number of bytes of extra storage
-** associated with each page cache entry. ^The szExtra parameter will
-** a number less than 250. SQLite will use the
-** extra szExtra bytes on each page to store metadata about the underlying
-** database page on disk. The value passed into szExtra depends
-** on the SQLite version, the target platform, and how SQLite was compiled.
-** ^The third 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
-** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
-** The pBuf element of the returned sqlite3_pcache_page object will be a
-** pointer to a buffer of szPage bytes used to store the content of a
-** single database page. The pExtra element of sqlite3_pcache_page will be
-** a pointer to the szExtra bytes of extra storage that SQLite has requested
-** for each entry in the page cache.
-**
-** 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 | Behavior 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_methods2
-** functions.
-**
-** [[the xShrink() page cache method]]
-** ^SQLite invokes the xShrink() method when it wants the page cache to
-** free up as much of heap memory as possible. The page cache implementation
-** is not obligated to free any memory, but well-behaved implementations should
-** do their best.
-*/
-typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
-struct sqlite3_pcache_methods2 {
- int iVersion;
- void *pArg;
- int (*xInit)(void*);
- void (*xShutdown)(void*);
- sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
- void (*xCachesize)(sqlite3_pcache*, int nCachesize);
- int (*xPagecount)(sqlite3_pcache*);
- sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
- void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
- void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
- unsigned oldKey, unsigned newKey);
- void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
- void (*xDestroy)(sqlite3_pcache*);
- void (*xShrink)(sqlite3_pcache*);
-};
-
-/*
-** This is the obsolete pcache_methods object that has now been replaced
-** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
-** retained in the header file for backwards compatibility only.
-*/
-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*);
-};
-
-
-/*
-** 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:
-**
-** - sqlite3_backup_init() is called once to initialize the
-** backup,
-**
- sqlite3_backup_step() is called one or more times to transfer
-** the data between the two databases, and finally
-**
- 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.
-**
-** ^A call to sqlite3_backup_init() will fail, returning NULL, if
-** there is already a read or read-write transaction open on the
-** destination database.
-**
-** ^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
-**
-** - the destination database was opened read-only, or
-**
- the destination database is using write-ahead-log journaling
-** and the destination and source page sizes differ, or
-**
- 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()
-**
-** ^The sqlite3_backup_remaining() routine returns the number of pages still
-** to be backed up at the conclusion of the most recent sqlite3_backup_step().
-** ^The sqlite3_backup_pagecount() routine returns the total number of pages
-** in the source database at the conclusion of the most recent
-** sqlite3_backup_step().
-** ^(The values returned by these functions are only updated by
-** sqlite3_backup_step(). If the source database is modified in a way that
-** changes the size of the source database or the number of pages remaining,
-** those changes are not reflected in the output of sqlite3_backup_pagecount()
-** and sqlite3_backup_remaining() until after the next
-** sqlite3_backup_step().)^
-**
-** 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 */
- const char *zDestName, /* Destination database name */
- sqlite3 *pSource, /* Source database handle */
- const char *zSourceName /* Source database name */
-);
-SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
-SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
-SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
-SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
-
-/*
-** CAPI3REF: Unlock Notification
-** METHOD: sqlite3
-**
-** ^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_stricmp()] and [sqlite3_strnicmp()] APIs allow 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_stricmp(const char *, const char *);
-SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
-
-/*
-** CAPI3REF: String Globbing
-*
-** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
-** string X matches the [GLOB] pattern P.
-** ^The definition of [GLOB] pattern matching used in
-** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
-** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
-** is case sensitive.
-**
-** Note that this routine returns zero on a match and non-zero if the strings
-** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
-**
-** See also: [sqlite3_strlike()].
-*/
-SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
-
-/*
-** CAPI3REF: String LIKE Matching
-*
-** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
-** string X matches the [LIKE] pattern P with escape character E.
-** ^The definition of [LIKE] pattern matching used in
-** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
-** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
-** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
-** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
-** insensitive - equivalent upper and lower case ASCII characters match
-** one another.
-**
-** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
-** only ASCII characters are case folded.
-**
-** Note that this routine returns zero on a match and non-zero if the strings
-** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
-**
-** See also: [sqlite3_strglob()].
-*/
-SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
-
-/*
-** 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, const char *zFormat, ...);
-
-/*
-** CAPI3REF: Write-Ahead Log Commit Hook
-** METHOD: sqlite3
-**
-** ^The [sqlite3_wal_hook()] function is used to register a callback that
-** is invoked each time data is committed to a database in 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
-** 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
-** METHOD: sqlite3
-**
-** ^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.
-**
-** ^Checkpoints initiated by this mechanism are
-** [sqlite3_wal_checkpoint_v2|PASSIVE].
-**
-** ^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
-** is only necessary if the default setting is found to be suboptimal
-** for a particular application.
-*/
-SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
-
-/*
-** CAPI3REF: Checkpoint a database
-** METHOD: sqlite3
-**
-** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
-** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
-**
-** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
-** [write-ahead log] for database X on [database connection] D to be
-** transferred into the database file and for the write-ahead log to
-** be reset. See the [checkpointing] documentation for addition
-** information.
-**
-** This interface used to be the only way to cause a checkpoint to
-** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
-** interface was added. This interface is retained for backwards
-** compatibility and as a convenience for applications that need to manually
-** start a callback but which do not need the full power (and corresponding
-** complication) of [sqlite3_wal_checkpoint_v2()].
-*/
-SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
-
-/*
-** CAPI3REF: Checkpoint a database
-** METHOD: sqlite3
-**
-** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
-** operation on database X of [database connection] D in mode M. Status
-** information is written back into integers pointed to by L and C.)^
-** ^(The M parameter must be a valid [checkpoint mode]:)^
-**
-**
-** - SQLITE_CHECKPOINT_PASSIVE
-
-** ^Checkpoint as many frames as possible without waiting for any database
-** readers or writers to finish, then sync the database file if all frames
-** in the log were checkpointed. ^The [busy-handler callback]
-** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
-** ^On the other hand, passive mode might leave the checkpoint unfinished
-** if there are concurrent readers or writers.
-**
-**
- SQLITE_CHECKPOINT_FULL
-
-** ^This mode blocks (it invokes the
-** [sqlite3_busy_handler|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 mode blocks new database writers while it is pending,
-** but new database readers are allowed to continue unimpeded.
-**
-**
- SQLITE_CHECKPOINT_RESTART
-
-** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
-** that 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 writer will restart the log file from the beginning.
-** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
-** database writer attempts while it is pending, but does not impede readers.
-**
-**
- SQLITE_CHECKPOINT_TRUNCATE
-
-** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
-** addition that it also truncates the log file to zero bytes just prior
-** to a successful return.
-**
-**
-** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
-** the log file or to -1 if the checkpoint could not run because
-** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
-** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
-** log file (including any that were already checkpointed before the function
-** was called) or to -1 if the checkpoint could not run due to an error or
-** because the database is not in WAL mode. ^Note that upon successful
-** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
-** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
-**
-** ^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, RESTART and TRUNCATE 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 [attached] to
-** [database connection] db. 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 at the end. ^If any other
-** error occurs while processing an attached database, processing is abandoned
-** and the error code is 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.
-**
-** ^Unless it returns SQLITE_MISUSE,
-** the sqlite3_wal_checkpoint_v2() interface
-** sets the error information that is queried by
-** [sqlite3_errcode()] and [sqlite3_errmsg()].
-**
-** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
-** from SQL.
-*/
-SQLITE_API int sqlite3_wal_checkpoint_v2(
- sqlite3 *db, /* Database handle */
- const char *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 Mode Values
-** KEYWORDS: {checkpoint mode}
-**
-** These constants define all valid values for the "checkpoint mode" passed
-** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
-** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
-** meaning of each of these checkpoint modes.
-*/
-#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
-#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
-#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
-#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
-
-/*
-** 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]]
-** - 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
-
-/*
-** 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: Determine If Virtual Table Column Access Is For UPDATE
-**
-** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
-** method of a [virtual table], then it returns true if and only if the
-** column is being fetched as part of an UPDATE operation during which the
-** column value will not change. Applications might use this to substitute
-** a return value that is less expensive to compute and that the corresponding
-** [xUpdate] method understands as a "no-change" value.
-**
-** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
-** the column is not changed by the UPDATE statement, then the xColumn
-** method can optionally return without setting a result, without calling
-** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
-** In that case, [sqlite3_value_nochange(X)] will return true for the
-** same column in the [xUpdate] method.
-*/
-SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
-
-/*
-** CAPI3REF: Determine The Collation For a Virtual Table Constraint
-**
-** This function may only be called from within a call to the [xBestIndex]
-** method of a [virtual table].
-**
-** The first argument must be the sqlite3_index_info object that is the
-** first parameter to the xBestIndex() method. The second argument must be
-** an index into the aConstraint[] array belonging to the sqlite3_index_info
-** structure passed to xBestIndex. This function returns a pointer to a buffer
-** containing the name of the collation sequence for the corresponding
-** constraint.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
-
-/*
-** CAPI3REF: Conflict resolution modes
-** KEYWORDS: {conflict resolution mode}
-**
-** 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
-/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
-#define SQLITE_FAIL 3
-/* #define SQLITE_ABORT 4 // Also an error code */
-#define SQLITE_REPLACE 5
-
-/*
-** CAPI3REF: Prepared Statement Scan Status Opcodes
-** KEYWORDS: {scanstatus options}
-**
-** The following constants can be used for the T parameter to the
-** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
-** different metric for sqlite3_stmt_scanstatus() to return.
-**
-** When the value returned to V is a string, space to hold that string is
-** managed by the prepared statement S and will be automatically freed when
-** S is finalized.
-**
-**
-** [[SQLITE_SCANSTAT_NLOOP]] - SQLITE_SCANSTAT_NLOOP
-** - ^The [sqlite3_int64] variable pointed to by the T parameter will be
-** set to the total number of times that the X-th loop has run.
-**
-** [[SQLITE_SCANSTAT_NVISIT]] - SQLITE_SCANSTAT_NVISIT
-** - ^The [sqlite3_int64] variable pointed to by the T parameter will be set
-** to the total number of rows examined by all iterations of the X-th loop.
-**
-** [[SQLITE_SCANSTAT_EST]] - SQLITE_SCANSTAT_EST
-** - ^The "double" variable pointed to by the T parameter will be set to the
-** query planner's estimate for the average number of rows output from each
-** iteration of the X-th loop. If the query planner's estimates was accurate,
-** then this value will approximate the quotient NVISIT/NLOOP and the
-** product of this value for all prior loops with the same SELECTID will
-** be the NLOOP value for the current loop.
-**
-** [[SQLITE_SCANSTAT_NAME]]
- SQLITE_SCANSTAT_NAME
-** - ^The "const char *" variable pointed to by the T parameter will be set
-** to a zero-terminated UTF-8 string containing the name of the index or table
-** used for the X-th loop.
-**
-** [[SQLITE_SCANSTAT_EXPLAIN]]
- SQLITE_SCANSTAT_EXPLAIN
-** - ^The "const char *" variable pointed to by the T parameter will be set
-** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
-** description for the X-th loop.
-**
-** [[SQLITE_SCANSTAT_SELECTID]]
- SQLITE_SCANSTAT_SELECT
-** - ^The "int" variable pointed to by the T parameter will be set to the
-** "select-id" for the X-th loop. The select-id identifies which query or
-** subquery the loop is part of. The main query has a select-id of zero.
-** The select-id is the same value as is output in the first column
-** of an [EXPLAIN QUERY PLAN] query.
-**
-*/
-#define SQLITE_SCANSTAT_NLOOP 0
-#define SQLITE_SCANSTAT_NVISIT 1
-#define SQLITE_SCANSTAT_EST 2
-#define SQLITE_SCANSTAT_NAME 3
-#define SQLITE_SCANSTAT_EXPLAIN 4
-#define SQLITE_SCANSTAT_SELECTID 5
-
-/*
-** CAPI3REF: Prepared Statement Scan Status
-** METHOD: sqlite3_stmt
-**
-** This interface returns information about the predicted and measured
-** performance for pStmt. Advanced applications can use this
-** interface to compare the predicted and the measured performance and
-** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
-**
-** Since this interface is expected to be rarely used, it is only
-** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
-** compile-time option.
-**
-** The "iScanStatusOp" parameter determines which status information to return.
-** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
-** of this interface is undefined.
-** ^The requested measurement is written into a variable pointed to by
-** the "pOut" parameter.
-** Parameter "idx" identifies the specific loop to retrieve statistics for.
-** Loops are numbered starting from zero. ^If idx is out of range - less than
-** zero or greater than or equal to the total number of loops used to implement
-** the statement - a non-zero value is returned and the variable that pOut
-** points to is unchanged.
-**
-** ^Statistics might not be available for all loops in all statements. ^In cases
-** where there exist loops with no available statistics, this function behaves
-** as if the loop did not exist - it returns non-zero and leave the variable
-** that pOut points to unchanged.
-**
-** See also: [sqlite3_stmt_scanstatus_reset()]
-*/
-SQLITE_API int sqlite3_stmt_scanstatus(
- sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
- int idx, /* Index of loop to report on */
- int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
- void *pOut /* Result written here */
-);
-
-/*
-** CAPI3REF: Zero Scan-Status Counters
-** METHOD: sqlite3_stmt
-**
-** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
-**
-** This API is only available if the library is built with pre-processor
-** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
-*/
-SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
-
-/*
-** CAPI3REF: Flush caches to disk mid-transaction
-**
-** ^If a write-transaction is open on [database connection] D when the
-** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
-** pages in the pager-cache that are not currently in use are written out
-** to disk. A dirty page may be in use if a database cursor created by an
-** active SQL statement is reading from it, or if it is page 1 of a database
-** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
-** interface flushes caches for all schemas - "main", "temp", and
-** any [attached] databases.
-**
-** ^If this function needs to obtain extra database locks before dirty pages
-** can be flushed to disk, it does so. ^If those locks cannot be obtained
-** immediately and there is a busy-handler callback configured, it is invoked
-** in the usual manner. ^If the required lock still cannot be obtained, then
-** the database is skipped and an attempt made to flush any dirty pages
-** belonging to the next (if any) database. ^If any databases are skipped
-** because locks cannot be obtained, but no other error occurs, this
-** function returns SQLITE_BUSY.
-**
-** ^If any other error occurs while flushing dirty pages to disk (for
-** example an IO error or out-of-memory condition), then processing is
-** abandoned and an SQLite [error code] is returned to the caller immediately.
-**
-** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
-**
-** ^This function does not set the database handle error code or message
-** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
-*/
-SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
-
-/*
-** CAPI3REF: The pre-update hook.
-**
-** ^These interfaces are only available if SQLite is compiled using the
-** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
-**
-** ^The [sqlite3_preupdate_hook()] interface registers a callback function
-** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
-** on a database table.
-** ^At most one preupdate hook may be registered at a time on a single
-** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
-** the previous setting.
-** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
-** with a NULL pointer as the second parameter.
-** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
-** the first parameter to callbacks.
-**
-** ^The preupdate hook only fires for changes to real database tables; the
-** preupdate hook is not invoked for changes to [virtual tables] or to
-** system tables like sqlite_master or sqlite_stat1.
-**
-** ^The second parameter to the preupdate callback is a pointer to
-** the [database connection] that registered the preupdate hook.
-** ^The third parameter to the preupdate callback is one of the constants
-** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
-** kind of update operation that is about to occur.
-** ^(The fourth parameter to the preupdate callback is the name of the
-** database within the database connection that is being modified. This
-** will be "main" for the main database or "temp" for TEMP tables or
-** the name given after the AS keyword in the [ATTACH] statement for attached
-** databases.)^
-** ^The fifth parameter to the preupdate callback is the name of the
-** table that is being modified.
-**
-** For an UPDATE or DELETE operation on a [rowid table], the sixth
-** parameter passed to the preupdate callback is the initial [rowid] of the
-** row being modified or deleted. For an INSERT operation on a rowid table,
-** or any operation on a WITHOUT ROWID table, the value of the sixth
-** parameter is undefined. For an INSERT or UPDATE on a rowid table the
-** seventh parameter is the final rowid value of the row being inserted
-** or updated. The value of the seventh parameter passed to the callback
-** function is not defined for operations on WITHOUT ROWID tables, or for
-** INSERT operations on rowid tables.
-**
-** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
-** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
-** provide additional information about a preupdate event. These routines
-** may only be called from within a preupdate callback. Invoking any of
-** these routines from outside of a preupdate callback or with a
-** [database connection] pointer that is different from the one supplied
-** to the preupdate callback results in undefined and probably undesirable
-** behavior.
-**
-** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
-** in the row that is being inserted, updated, or deleted.
-**
-** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
-** a [protected sqlite3_value] that contains the value of the Nth column of
-** the table row before it is updated. The N parameter must be between 0
-** and one less than the number of columns or the behavior will be
-** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
-** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
-** behavior is undefined. The [sqlite3_value] that P points to
-** will be destroyed when the preupdate callback returns.
-**
-** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
-** a [protected sqlite3_value] that contains the value of the Nth column of
-** the table row after it is updated. The N parameter must be between 0
-** and one less than the number of columns or the behavior will be
-** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
-** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
-** behavior is undefined. The [sqlite3_value] that P points to
-** will be destroyed when the preupdate callback returns.
-**
-** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
-** callback was invoked as a result of a direct insert, update, or delete
-** operation; or 1 for inserts, updates, or deletes invoked by top-level
-** triggers; or 2 for changes resulting from triggers called by top-level
-** triggers; and so forth.
-**
-** See also: [sqlite3_update_hook()]
-*/
-#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
-SQLITE_API void *sqlite3_preupdate_hook(
- sqlite3 *db,
- void(*xPreUpdate)(
- void *pCtx, /* Copy of third arg to preupdate_hook() */
- sqlite3 *db, /* Database handle */
- int op, /* SQLITE_UPDATE, DELETE or INSERT */
- char const *zDb, /* Database name */
- char const *zName, /* Table name */
- sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
- sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
- ),
- void*
-);
-SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
-SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
-SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
-SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
-#endif
-
-/*
-** CAPI3REF: Low-level system error code
-**
-** ^Attempt to return the underlying operating system error code or error
-** number that caused the most recent I/O error or failure to open a file.
-** The return value is OS-dependent. For example, on unix systems, after
-** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
-** called to get back the underlying "errno" that caused the problem, such
-** as ENOSPC, EAUTH, EISDIR, and so forth.
-*/
-SQLITE_API int sqlite3_system_errno(sqlite3*);
-
-/*
-** CAPI3REF: Database Snapshot
-** KEYWORDS: {snapshot} {sqlite3_snapshot}
-**
-** An instance of the snapshot object records the state of a [WAL mode]
-** database for some specific point in history.
-**
-** In [WAL mode], multiple [database connections] that are open on the
-** same database file can each be reading a different historical version
-** of the database file. When a [database connection] begins a read
-** transaction, that connection sees an unchanging copy of the database
-** as it existed for the point in time when the transaction first started.
-** Subsequent changes to the database from other connections are not seen
-** by the reader until a new read transaction is started.
-**
-** The sqlite3_snapshot object records state information about an historical
-** version of the database file so that it is possible to later open a new read
-** transaction that sees that historical version of the database rather than
-** the most recent version.
-*/
-typedef struct sqlite3_snapshot {
- unsigned char hidden[48];
-} sqlite3_snapshot;
-
-/*
-** CAPI3REF: Record A Database Snapshot
-** CONSTRUCTOR: sqlite3_snapshot
-**
-** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
-** new [sqlite3_snapshot] object that records the current state of
-** schema S in database connection D. ^On success, the
-** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
-** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
-** If there is not already a read-transaction open on schema S when
-** this function is called, one is opened automatically.
-**
-** The following must be true for this function to succeed. If any of
-** the following statements are false when sqlite3_snapshot_get() is
-** called, SQLITE_ERROR is returned. The final value of *P is undefined
-** in this case.
-**
-**
-** - The database handle must not be in [autocommit mode].
-**
-**
- Schema S of [database connection] D must be a [WAL mode] database.
-**
-**
- There must not be a write transaction open on schema S of database
-** connection D.
-**
-**
- One or more transactions must have been written to the current wal
-** file since it was created on disk (by any connection). This means
-** that a snapshot cannot be taken on a wal mode database with no wal
-** file immediately after it is first opened. At least one transaction
-** must be written to it first.
-**
-**
-** This function may also return SQLITE_NOMEM. If it is called with the
-** database handle in autocommit mode but fails for some other reason,
-** whether or not a read transaction is opened on schema S is undefined.
-**
-** The [sqlite3_snapshot] object returned from a successful call to
-** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
-** to avoid a memory leak.
-**
-** The [sqlite3_snapshot_get()] interface is only available when the
-** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
- sqlite3 *db,
- const char *zSchema,
- sqlite3_snapshot **ppSnapshot
-);
-
-/*
-** CAPI3REF: Start a read transaction on an historical snapshot
-** METHOD: sqlite3_snapshot
-**
-** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
-** transaction or upgrades an existing one for schema S of
-** [database connection] D such that the read transaction refers to
-** historical [snapshot] P, rather than the most recent change to the
-** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
-** on success or an appropriate [error code] if it fails.
-**
-** ^In order to succeed, the database connection must not be in
-** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
-** is already a read transaction open on schema S, then the database handle
-** must have no active statements (SELECT statements that have been passed
-** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
-** SQLITE_ERROR is returned if either of these conditions is violated, or
-** if schema S does not exist, or if the snapshot object is invalid.
-**
-** ^A call to sqlite3_snapshot_open() will fail to open if the specified
-** snapshot has been overwritten by a [checkpoint]. In this case
-** SQLITE_ERROR_SNAPSHOT is returned.
-**
-** If there is already a read transaction open when this function is
-** invoked, then the same read transaction remains open (on the same
-** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
-** is returned. If another error code - for example SQLITE_PROTOCOL or an
-** SQLITE_IOERR error code - is returned, then the final state of the
-** read transaction is undefined. If SQLITE_OK is returned, then the
-** read transaction is now open on database snapshot P.
-**
-** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
-** database connection D does not know that the database file for
-** schema S is in [WAL mode]. A database connection might not know
-** that the database file is in [WAL mode] if there has been no prior
-** I/O on that database connection, or if the database entered [WAL mode]
-** after the most recent I/O on the database connection.)^
-** (Hint: Run "[PRAGMA application_id]" against a newly opened
-** database connection in order to make it ready to use snapshots.)
-**
-** The [sqlite3_snapshot_open()] interface is only available when the
-** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
- sqlite3 *db,
- const char *zSchema,
- sqlite3_snapshot *pSnapshot
-);
-
-/*
-** CAPI3REF: Destroy a snapshot
-** DESTRUCTOR: sqlite3_snapshot
-**
-** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
-** The application must eventually free every [sqlite3_snapshot] object
-** using this routine to avoid a memory leak.
-**
-** The [sqlite3_snapshot_free()] interface is only available when the
-** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
-
-/*
-** CAPI3REF: Compare the ages of two snapshot handles.
-** METHOD: sqlite3_snapshot
-**
-** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
-** of two valid snapshot handles.
-**
-** If the two snapshot handles are not associated with the same database
-** file, the result of the comparison is undefined.
-**
-** Additionally, the result of the comparison is only valid if both of the
-** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
-** last time the wal file was deleted. The wal file is deleted when the
-** database is changed back to rollback mode or when the number of database
-** clients drops to zero. If either snapshot handle was obtained before the
-** wal file was last deleted, the value returned by this function
-** is undefined.
-**
-** Otherwise, this API returns a negative value if P1 refers to an older
-** snapshot than P2, zero if the two handles refer to the same database
-** snapshot, and a positive value if P1 is a newer snapshot than P2.
-**
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_SNAPSHOT] option.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
- sqlite3_snapshot *p1,
- sqlite3_snapshot *p2
-);
-
-/*
-** CAPI3REF: Recover snapshots from a wal file
-** METHOD: sqlite3_snapshot
-**
-** If a [WAL file] remains on disk after all database connections close
-** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
-** or because the last process to have the database opened exited without
-** calling [sqlite3_close()]) and a new connection is subsequently opened
-** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
-** will only be able to open the last transaction added to the WAL file
-** even though the WAL file contains other valid transactions.
-**
-** This function attempts to scan the WAL file associated with database zDb
-** of database handle db and make all valid snapshots available to
-** sqlite3_snapshot_open(). It is an error if there is already a read
-** transaction open on the database, or if the database is not a WAL mode
-** database.
-**
-** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
-**
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_SNAPSHOT] option.
-*/
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
-
-/*
-** CAPI3REF: Serialize a database
-**
-** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
-** that is a serialization of the S database on [database connection] D.
-** If P is not a NULL pointer, then the size of the database in bytes
-** is written into *P.
-**
-** For an ordinary on-disk database file, the serialization is just a
-** copy of the disk file. For an in-memory database or a "TEMP" database,
-** the serialization is the same sequence of bytes which would be written
-** to disk if that database where backed up to disk.
-**
-** The usual case is that sqlite3_serialize() copies the serialization of
-** the database into memory obtained from [sqlite3_malloc64()] and returns
-** a pointer to that memory. The caller is responsible for freeing the
-** returned value to avoid a memory leak. However, if the F argument
-** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
-** are made, and the sqlite3_serialize() function will return a pointer
-** to the contiguous memory representation of the database that SQLite
-** is currently using for that database, or NULL if the no such contiguous
-** memory representation of the database exists. A contiguous memory
-** representation of the database will usually only exist if there has
-** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
-** values of D and S.
-** The size of the database is written into *P even if the
-** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
-** of the database exists.
-**
-** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
-** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
-** allocation error occurs.
-**
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
-*/
-SQLITE_API unsigned char *sqlite3_serialize(
- sqlite3 *db, /* The database connection */
- const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
- sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
- unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
-);
-
-/*
-** CAPI3REF: Flags for sqlite3_serialize
-**
-** Zero or more of the following constants can be OR-ed together for
-** the F argument to [sqlite3_serialize(D,S,P,F)].
-**
-** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
-** a pointer to contiguous in-memory database that it is currently using,
-** without making a copy of the database. If SQLite is not currently using
-** a contiguous in-memory database, then this option causes
-** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
-** using a contiguous in-memory database if it has been initialized by a
-** prior call to [sqlite3_deserialize()].
-*/
-#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
-
-/*
-** CAPI3REF: Deserialize a database
-**
-** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
-** [database connection] D to disconnect from database S and then
-** reopen S as an in-memory database based on the serialization contained
-** in P. The serialized database P is N bytes in size. M is the size of
-** the buffer P, which might be larger than N. If M is larger than N, and
-** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
-** permitted to add content to the in-memory database as long as the total
-** size does not exceed M bytes.
-**
-** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
-** invoke sqlite3_free() on the serialization buffer when the database
-** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
-** SQLite will try to increase the buffer size using sqlite3_realloc64()
-** if writes on the database cause it to grow larger than M bytes.
-**
-** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
-** database is currently in a read transaction or is involved in a backup
-** operation.
-**
-** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
-** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
-** [sqlite3_free()] is invoked on argument P prior to returning.
-**
-** This interface is only available if SQLite is compiled with the
-** [SQLITE_ENABLE_DESERIALIZE] option.
-*/
-SQLITE_API int sqlite3_deserialize(
- sqlite3 *db, /* The database connection */
- const char *zSchema, /* Which DB to reopen with the deserialization */
- unsigned char *pData, /* The serialized database content */
- sqlite3_int64 szDb, /* Number bytes in the deserialization */
- sqlite3_int64 szBuf, /* Total size of buffer pData[] */
- unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
-);
-
-/*
-** CAPI3REF: Flags for sqlite3_deserialize()
-**
-** The following are allowed values for 6th argument (the F argument) to
-** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
-**
-** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
-** in the P argument is held in memory obtained from [sqlite3_malloc64()]
-** and that SQLite should take ownership of this memory and automatically
-** free it when it has finished using it. Without this flag, the caller
-** is responsible for freeing any dynamically allocated memory.
-**
-** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
-** grow the size of the database using calls to [sqlite3_realloc64()]. This
-** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
-** Without this flag, the deserialized database cannot increase in size beyond
-** the number of bytes specified by the M parameter.
-**
-** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
-** should be treated as read-only.
-*/
-#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
-#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
-#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
-
-/*
-** Undo the hack that converts floating point types to integer for
-** builds on processors without floating point support.
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# undef double
-#endif
-
-#if 0
-} /* End of the 'extern "C"' block */
-#endif
-#endif /* SQLITE3_H */
-
-/******** Begin file sqlite3rtree.h *********/
-/*
-** 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.
-**
-*************************************************************************
-*/
-
-#ifndef _SQLITE3RTREE_H_
-#define _SQLITE3RTREE_H_
-
-
-#if 0
-extern "C" {
-#endif
-
-typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
-typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
-
-/* The double-precision datatype used by RTree depends on the
-** SQLITE_RTREE_INT_ONLY compile-time option.
-*/
-#ifdef SQLITE_RTREE_INT_ONLY
- typedef sqlite3_int64 sqlite3_rtree_dbl;
-#else
- typedef double sqlite3_rtree_dbl;
-#endif
-
-/*
-** 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,
- const char *zGeom,
- int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
- 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[] */
- sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
- void *pUser; /* Callback implementation user data */
- void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
-};
-
-/*
-** Register a 2nd-generation geometry callback named zScore that can be
-** used as part of an R-Tree geometry query as follows:
-**
-** SELECT ... FROM WHERE MATCH $zQueryFunc(... params ...)
-*/
-SQLITE_API int sqlite3_rtree_query_callback(
- sqlite3 *db,
- const char *zQueryFunc,
- int (*xQueryFunc)(sqlite3_rtree_query_info*),
- void *pContext,
- void (*xDestructor)(void*)
-);
-
-
-/*
-** A pointer to a structure of the following type is passed as the
-** argument to scored geometry callback registered using
-** sqlite3_rtree_query_callback().
-**
-** Note that the first 5 fields of this structure are identical to
-** sqlite3_rtree_geometry. This structure is a subclass of
-** sqlite3_rtree_geometry.
-*/
-struct sqlite3_rtree_query_info {
- void *pContext; /* pContext from when function registered */
- int nParam; /* Number of function parameters */
- sqlite3_rtree_dbl *aParam; /* value of function parameters */
- void *pUser; /* callback can use this, if desired */
- void (*xDelUser)(void*); /* function to free pUser */
- sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
- unsigned int *anQueue; /* Number of pending entries in the queue */
- int nCoord; /* Number of coordinates */
- int iLevel; /* Level of current node or entry */
- int mxLevel; /* The largest iLevel value in the tree */
- sqlite3_int64 iRowid; /* Rowid for current entry */
- sqlite3_rtree_dbl rParentScore; /* Score of parent node */
- int eParentWithin; /* Visibility of parent node */
- int eWithin; /* OUT: Visibility */
- sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
- /* The following fields are only available in 3.8.11 and later */
- sqlite3_value **apSqlParam; /* Original SQL values of parameters */
-};
-
-/*
-** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
-*/
-#define NOT_WITHIN 0 /* Object completely outside of query region */
-#define PARTLY_WITHIN 1 /* Object partially overlaps query region */
-#define FULLY_WITHIN 2 /* Object fully contained within query region */
-
-
-#if 0
-} /* end of the 'extern "C"' block */
-#endif
-
-#endif /* ifndef _SQLITE3RTREE_H_ */
-
-/******** End of sqlite3rtree.h *********/
-/******** Begin file sqlite3session.h *********/
-
-#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
-#define __SQLITESESSION_H_ 1
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#if 0
-extern "C" {
-#endif
-
-
-/*
-** CAPI3REF: Session Object Handle
-**
-** An instance of this object is a [session] that can be used to
-** record changes to a database.
-*/
-typedef struct sqlite3_session sqlite3_session;
-
-/*
-** CAPI3REF: Changeset Iterator Handle
-**
-** An instance of this object acts as a cursor for iterating
-** over the elements of a [changeset] or [patchset].
-*/
-typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
-
-/*
-** CAPI3REF: Create A New Session Object
-** CONSTRUCTOR: sqlite3_session
-**
-** Create a new session object attached to database handle db. If successful,
-** a pointer to the new object is written to *ppSession and SQLITE_OK is
-** returned. If an error occurs, *ppSession is set to NULL and an SQLite
-** error code (e.g. SQLITE_NOMEM) is returned.
-**
-** It is possible to create multiple session objects attached to a single
-** database handle.
-**
-** Session objects created using this function should be deleted using the
-** [sqlite3session_delete()] function before the database handle that they
-** are attached to is itself closed. If the database handle is closed before
-** the session object is deleted, then the results of calling any session
-** module function, including [sqlite3session_delete()] on the session object
-** are undefined.
-**
-** Because the session module uses the [sqlite3_preupdate_hook()] API, it
-** is not possible for an application to register a pre-update hook on a
-** database handle that has one or more session objects attached. Nor is
-** it possible to create a session object attached to a database handle for
-** which a pre-update hook is already defined. The results of attempting
-** either of these things are undefined.
-**
-** The session object will be used to create changesets for tables in
-** database zDb, where zDb is either "main", or "temp", or the name of an
-** attached database. It is not an error if database zDb is not attached
-** to the database when the session object is created.
-*/
-SQLITE_API int sqlite3session_create(
- sqlite3 *db, /* Database handle */
- const char *zDb, /* Name of db (e.g. "main") */
- sqlite3_session **ppSession /* OUT: New session object */
-);
-
-/*
-** CAPI3REF: Delete A Session Object
-** DESTRUCTOR: sqlite3_session
-**
-** Delete a session object previously allocated using
-** [sqlite3session_create()]. Once a session object has been deleted, the
-** results of attempting to use pSession with any other session module
-** function are undefined.
-**
-** Session objects must be deleted before the database handle to which they
-** are attached is closed. Refer to the documentation for
-** [sqlite3session_create()] for details.
-*/
-SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
-
-
-/*
-** CAPI3REF: Enable Or Disable A Session Object
-** METHOD: sqlite3_session
-**
-** Enable or disable the recording of changes by a session object. When
-** enabled, a session object records changes made to the database. When
-** disabled - it does not. A newly created session object is enabled.
-** Refer to the documentation for [sqlite3session_changeset()] for further
-** details regarding how enabling and disabling a session object affects
-** the eventual changesets.
-**
-** Passing zero to this function disables the session. Passing a value
-** greater than zero enables it. Passing a value less than zero is a
-** no-op, and may be used to query the current state of the session.
-**
-** The return value indicates the final state of the session object: 0 if
-** the session is disabled, or 1 if it is enabled.
-*/
-SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
-
-/*
-** CAPI3REF: Set Or Clear the Indirect Change Flag
-** METHOD: sqlite3_session
-**
-** Each change recorded by a session object is marked as either direct or
-** indirect. A change is marked as indirect if either:
-**
-**
-** - The session object "indirect" flag is set when the change is
-** made, or
-**
- The change is made by an SQL trigger or foreign key action
-** instead of directly as a result of a users SQL statement.
-**
-**
-** If a single row is affected by more than one operation within a session,
-** then the change is considered indirect if all operations meet the criteria
-** for an indirect change above, or direct otherwise.
-**
-** This function is used to set, clear or query the session object indirect
-** flag. If the second argument passed to this function is zero, then the
-** indirect flag is cleared. If it is greater than zero, the indirect flag
-** is set. Passing a value less than zero does not modify the current value
-** of the indirect flag, and may be used to query the current state of the
-** indirect flag for the specified session object.
-**
-** The return value indicates the final state of the indirect flag: 0 if
-** it is clear, or 1 if it is set.
-*/
-SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
-
-/*
-** CAPI3REF: Attach A Table To A Session Object
-** METHOD: sqlite3_session
-**
-** If argument zTab is not NULL, then it is the name of a table to attach
-** to the session object passed as the first argument. All subsequent changes
-** made to the table while the session object is enabled will be recorded. See
-** documentation for [sqlite3session_changeset()] for further details.
-**
-** Or, if argument zTab is NULL, then changes are recorded for all tables
-** in the database. If additional tables are added to the database (by
-** executing "CREATE TABLE" statements) after this call is made, changes for
-** the new tables are also recorded.
-**
-** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
-** defined as part of their CREATE TABLE statement. It does not matter if the
-** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
-** KEY may consist of a single column, or may be a composite key.
-**
-** It is not an error if the named table does not exist in the database. Nor
-** is it an error if the named table does not have a PRIMARY KEY. However,
-** no changes will be recorded in either of these scenarios.
-**
-** Changes are not recorded for individual rows that have NULL values stored
-** in one or more of their PRIMARY KEY columns.
-**
-** SQLITE_OK is returned if the call completes without error. Or, if an error
-** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
-**
-** Special sqlite_stat1 Handling
-**
-** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
-** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
-**
-** CREATE TABLE sqlite_stat1(tbl,idx,stat)
-**
-**
-** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
-** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
-** are recorded for rows for which (idx IS NULL) is true. However, for such
-** rows a zero-length blob (SQL value X'') is stored in the changeset or
-** patchset instead of a NULL value. This allows such changesets to be
-** manipulated by legacy implementations of sqlite3changeset_invert(),
-** concat() and similar.
-**
-** The sqlite3changeset_apply() function automatically converts the
-** zero-length blob back to a NULL value when updating the sqlite_stat1
-** table. However, if the application calls sqlite3changeset_new(),
-** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
-** iterator directly (including on a changeset iterator passed to a
-** conflict-handler callback) then the X'' value is returned. The application
-** must translate X'' to NULL itself if required.
-**
-** Legacy (older than 3.22.0) versions of the sessions module cannot capture
-** changes made to the sqlite_stat1 table. Legacy versions of the
-** sqlite3changeset_apply() function silently ignore any modifications to the
-** sqlite_stat1 table that are part of a changeset or patchset.
-*/
-SQLITE_API int sqlite3session_attach(
- sqlite3_session *pSession, /* Session object */
- const char *zTab /* Table name */
-);
-
-/*
-** CAPI3REF: Set a table filter on a Session Object.
-** METHOD: sqlite3_session
-**
-** The second argument (xFilter) is the "filter callback". For changes to rows
-** in tables that are not attached to the Session object, the filter is called
-** to determine whether changes to the table's rows should be tracked or not.
-** If xFilter returns 0, changes is not tracked. Note that once a table is
-** attached, xFilter will not be called again.
-*/
-SQLITE_API void sqlite3session_table_filter(
- sqlite3_session *pSession, /* Session object */
- int(*xFilter)(
- void *pCtx, /* Copy of third arg to _filter_table() */
- const char *zTab /* Table name */
- ),
- void *pCtx /* First argument passed to xFilter */
-);
-
-/*
-** CAPI3REF: Generate A Changeset From A Session Object
-** METHOD: sqlite3_session
-**
-** Obtain a changeset containing changes to the tables attached to the
-** session object passed as the first argument. If successful,
-** set *ppChangeset to point to a buffer containing the changeset
-** and *pnChangeset to the size of the changeset in bytes before returning
-** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
-** zero and return an SQLite error code.
-**
-** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
-** each representing a change to a single row of an attached table. An INSERT
-** change contains the values of each field of a new database row. A DELETE
-** contains the original values of each field of a deleted database row. An
-** UPDATE change contains the original values of each field of an updated
-** database row along with the updated values for each updated non-primary-key
-** column. It is not possible for an UPDATE change to represent a change that
-** modifies the values of primary key columns. If such a change is made, it
-** is represented in a changeset as a DELETE followed by an INSERT.
-**
-** Changes are not recorded for rows that have NULL values stored in one or
-** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
-** no corresponding change is present in the changesets returned by this
-** function. If an existing row with one or more NULL values stored in
-** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
-** only an INSERT is appears in the changeset. Similarly, if an existing row
-** with non-NULL PRIMARY KEY values is updated so that one or more of its
-** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
-** DELETE change only.
-**
-** The contents of a changeset may be traversed using an iterator created
-** using the [sqlite3changeset_start()] API. A changeset may be applied to
-** a database with a compatible schema using the [sqlite3changeset_apply()]
-** API.
-**
-** Within a changeset generated by this function, all changes related to a
-** single table are grouped together. In other words, when iterating through
-** a changeset or when applying a changeset to a database, all changes related
-** to a single table are processed before moving on to the next table. Tables
-** are sorted in the same order in which they were attached (or auto-attached)
-** to the sqlite3_session object. The order in which the changes related to
-** a single table are stored is undefined.
-**
-** Following a successful call to this function, it is the responsibility of
-** the caller to eventually free the buffer that *ppChangeset points to using
-** [sqlite3_free()].
-**
-** Changeset Generation
-**
-** Once a table has been attached to a session object, the session object
-** records the primary key values of all new rows inserted into the table.
-** It also records the original primary key and other column values of any
-** deleted or updated rows. For each unique primary key value, data is only
-** recorded once - the first time a row with said primary key is inserted,
-** updated or deleted in the lifetime of the session.
-**
-** There is one exception to the previous paragraph: when a row is inserted,
-** updated or deleted, if one or more of its primary key columns contain a
-** NULL value, no record of the change is made.
-**
-** The session object therefore accumulates two types of records - those
-** that consist of primary key values only (created when the user inserts
-** a new record) and those that consist of the primary key values and the
-** original values of other table columns (created when the users deletes
-** or updates a record).
-**
-** When this function is called, the requested changeset is created using
-** both the accumulated records and the current contents of the database
-** file. Specifically:
-**
-**
-** - For each record generated by an insert, the database is queried
-** for a row with a matching primary key. If one is found, an INSERT
-** change is added to the changeset. If no such row is found, no change
-** is added to the changeset.
-**
-**
- For each record generated by an update or delete, the database is
-** queried for a row with a matching primary key. If such a row is
-** found and one or more of the non-primary key fields have been
-** modified from their original values, an UPDATE change is added to
-** the changeset. Or, if no such row is found in the table, a DELETE
-** change is added to the changeset. If there is a row with a matching
-** primary key in the database, but all fields contain their original
-** values, no change is added to the changeset.
-**
-**
-** This means, amongst other things, that if a row is inserted and then later
-** deleted while a session object is active, neither the insert nor the delete
-** will be present in the changeset. Or if a row is deleted and then later a
-** row with the same primary key values inserted while a session object is
-** active, the resulting changeset will contain an UPDATE change instead of
-** a DELETE and an INSERT.
-**
-** When a session object is disabled (see the [sqlite3session_enable()] API),
-** it does not accumulate records when rows are inserted, updated or deleted.
-** This may appear to have some counter-intuitive effects if a single row
-** is written to more than once during a session. For example, if a row
-** is inserted while a session object is enabled, then later deleted while
-** the same session object is disabled, no INSERT record will appear in the
-** changeset, even though the delete took place while the session was disabled.
-** Or, if one field of a row is updated while a session is disabled, and
-** another field of the same row is updated while the session is enabled, the
-** resulting changeset will contain an UPDATE change that updates both fields.
-*/
-SQLITE_API int sqlite3session_changeset(
- sqlite3_session *pSession, /* Session object */
- int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
- void **ppChangeset /* OUT: Buffer containing changeset */
-);
-
-/*
-** CAPI3REF: Load The Difference Between Tables Into A Session
-** METHOD: sqlite3_session
-**
-** If it is not already attached to the session object passed as the first
-** argument, this function attaches table zTbl in the same manner as the
-** [sqlite3session_attach()] function. If zTbl does not exist, or if it
-** does not have a primary key, this function is a no-op (but does not return
-** an error).
-**
-** Argument zFromDb must be the name of a database ("main", "temp" etc.)
-** attached to the same database handle as the session object that contains
-** a table compatible with the table attached to the session by this function.
-** A table is considered compatible if it:
-**
-**
-** - Has the same name,
-**
- Has the same set of columns declared in the same order, and
-**
- Has the same PRIMARY KEY definition.
-**
-**
-** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
-** are compatible but do not have any PRIMARY KEY columns, it is not an error
-** but no changes are added to the session object. As with other session
-** APIs, tables without PRIMARY KEYs are simply ignored.
-**
-** This function adds a set of changes to the session object that could be
-** used to update the table in database zFrom (call this the "from-table")
-** so that its content is the same as the table attached to the session
-** object (call this the "to-table"). Specifically:
-**
-**
-** - For each row (primary key) that exists in the to-table but not in
-** the from-table, an INSERT record is added to the session object.
-**
-**
- For each row (primary key) that exists in the to-table but not in
-** the from-table, a DELETE record is added to the session object.
-**
-**
- For each row (primary key) that exists in both tables, but features
-** different non-PK values in each, an UPDATE record is added to the
-** session.
-**
-**
-** To clarify, if this function is called and then a changeset constructed
-** using [sqlite3session_changeset()], then after applying that changeset to
-** database zFrom the contents of the two compatible tables would be
-** identical.
-**
-** It an error if database zFrom does not exist or does not contain the
-** required compatible table.
-**
-** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
-** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
-** may be set to point to a buffer containing an English language error
-** message. It is the responsibility of the caller to free this buffer using
-** sqlite3_free().
-*/
-SQLITE_API int sqlite3session_diff(
- sqlite3_session *pSession,
- const char *zFromDb,
- const char *zTbl,
- char **pzErrMsg
-);
-
-
-/*
-** CAPI3REF: Generate A Patchset From A Session Object
-** METHOD: sqlite3_session
-**
-** The differences between a patchset and a changeset are that:
-**
-**
-** - DELETE records consist of the primary key fields only. The
-** original values of other fields are omitted.
-**
- The original values of any modified fields are omitted from
-** UPDATE records.
-**
-**
-** A patchset blob may be used with up to date versions of all
-** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
-** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
-** attempting to use a patchset blob with old versions of the
-** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
-**
-** Because the non-primary key "old.*" fields are omitted, no
-** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
-** is passed to the sqlite3changeset_apply() API. Other conflict types work
-** in the same way as for changesets.
-**
-** Changes within a patchset are ordered in the same way as for changesets
-** generated by the sqlite3session_changeset() function (i.e. all changes for
-** a single table are grouped together, tables appear in the order in which
-** they were attached to the session object).
-*/
-SQLITE_API int sqlite3session_patchset(
- sqlite3_session *pSession, /* Session object */
- int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
- void **ppPatchset /* OUT: Buffer containing patchset */
-);
-
-/*
-** CAPI3REF: Test if a changeset has recorded any changes.
-**
-** Return non-zero if no changes to attached tables have been recorded by
-** the session object passed as the first argument. Otherwise, if one or
-** more changes have been recorded, return zero.
-**
-** Even if this function returns zero, it is possible that calling
-** [sqlite3session_changeset()] on the session handle may still return a
-** changeset that contains no changes. This can happen when a row in
-** an attached table is modified and then later on the original values
-** are restored. However, if this function returns non-zero, then it is
-** guaranteed that a call to sqlite3session_changeset() will return a
-** changeset containing zero changes.
-*/
-SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
-
-/*
-** CAPI3REF: Create An Iterator To Traverse A Changeset
-** CONSTRUCTOR: sqlite3_changeset_iter
-**
-** Create an iterator used to iterate through the contents of a changeset.
-** If successful, *pp is set to point to the iterator handle and SQLITE_OK
-** is returned. Otherwise, if an error occurs, *pp is set to zero and an
-** SQLite error code is returned.
-**
-** The following functions can be used to advance and query a changeset
-** iterator created by this function:
-**
-**
-** - [sqlite3changeset_next()]
-**
- [sqlite3changeset_op()]
-**
- [sqlite3changeset_new()]
-**
- [sqlite3changeset_old()]
-**
-**
-** It is the responsibility of the caller to eventually destroy the iterator
-** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
-** changeset (pChangeset) must remain valid until after the iterator is
-** destroyed.
-**
-** Assuming the changeset blob was created by one of the
-** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
-** [sqlite3changeset_invert()] functions, all changes within the changeset
-** that apply to a single table are grouped together. This means that when
-** an application iterates through a changeset using an iterator created by
-** this function, all changes that relate to a single table are visited
-** consecutively. There is no chance that the iterator will visit a change
-** the applies to table X, then one for table Y, and then later on visit
-** another change for table X.
-**
-** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
-** may be modified by passing a combination of
-** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
-**
-** Note that the sqlite3changeset_start_v2() API is still experimental
-** and therefore subject to change.
-*/
-SQLITE_API int sqlite3changeset_start(
- sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
- int nChangeset, /* Size of changeset blob in bytes */
- void *pChangeset /* Pointer to blob containing changeset */
-);
-SQLITE_API int sqlite3changeset_start_v2(
- sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
- int nChangeset, /* Size of changeset blob in bytes */
- void *pChangeset, /* Pointer to blob containing changeset */
- int flags /* SESSION_CHANGESETSTART_* flags */
-);
-
-/*
-** CAPI3REF: Flags for sqlite3changeset_start_v2
-**
-** The following flags may passed via the 4th parameter to
-** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
-**
-** SQLITE_CHANGESETAPPLY_INVERT
-** Invert the changeset while iterating through it. This is equivalent to
-** inverting a changeset using sqlite3changeset_invert() before applying it.
-** It is an error to specify this flag with a patchset.
-*/
-#define SQLITE_CHANGESETSTART_INVERT 0x0002
-
-
-/*
-** CAPI3REF: Advance A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** This function may only be used with iterators created by function
-** [sqlite3changeset_start()]. If it is called on an iterator passed to
-** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
-** is returned and the call has no effect.
-**
-** Immediately after an iterator is created by sqlite3changeset_start(), it
-** does not point to any change in the changeset. Assuming the changeset
-** is not empty, the first call to this function advances the iterator to
-** point to the first change in the changeset. Each subsequent call advances
-** the iterator to point to the next change in the changeset (if any). If
-** no error occurs and the iterator points to a valid change after a call
-** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
-** Otherwise, if all changes in the changeset have already been visited,
-** SQLITE_DONE is returned.
-**
-** If an error occurs, an SQLite error code is returned. Possible error
-** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
-** SQLITE_NOMEM.
-*/
-SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
-
-/*
-** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** The pIter argument passed to this function may either be an iterator
-** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
-** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
-** is not the case, this function returns [SQLITE_MISUSE].
-**
-** If argument pzTab is not NULL, then *pzTab is set to point to a
-** nul-terminated utf-8 encoded string containing the name of the table
-** affected by the current change. The buffer remains valid until either
-** sqlite3changeset_next() is called on the iterator or until the
-** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
-** set to the number of columns in the table affected by the change. If
-** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
-** is an indirect change, or false (0) otherwise. See the documentation for
-** [sqlite3session_indirect()] for a description of direct and indirect
-** changes. Finally, if pOp is not NULL, then *pOp is set to one of
-** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
-** type of change that the iterator currently points to.
-**
-** If no error occurs, SQLITE_OK is returned. If an error does occur, an
-** SQLite error code is returned. The values of the output variables may not
-** be trusted in this case.
-*/
-SQLITE_API int sqlite3changeset_op(
- sqlite3_changeset_iter *pIter, /* Iterator object */
- const char **pzTab, /* OUT: Pointer to table name */
- int *pnCol, /* OUT: Number of columns in table */
- int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
- int *pbIndirect /* OUT: True for an 'indirect' change */
-);
-
-/*
-** CAPI3REF: Obtain The Primary Key Definition Of A Table
-** METHOD: sqlite3_changeset_iter
-**
-** For each modified table, a changeset includes the following:
-**
-**
-** - The number of columns in the table, and
-**
- Which of those columns make up the tables PRIMARY KEY.
-**
-**
-** This function is used to find which columns comprise the PRIMARY KEY of
-** the table modified by the change that iterator pIter currently points to.
-** If successful, *pabPK is set to point to an array of nCol entries, where
-** nCol is the number of columns in the table. Elements of *pabPK are set to
-** 0x01 if the corresponding column is part of the tables primary key, or
-** 0x00 if it is not.
-**
-** If argument pnCol is not NULL, then *pnCol is set to the number of columns
-** in the table.
-**
-** If this function is called when the iterator does not point to a valid
-** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
-** SQLITE_OK is returned and the output variables populated as described
-** above.
-*/
-SQLITE_API int sqlite3changeset_pk(
- sqlite3_changeset_iter *pIter, /* Iterator object */
- unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
- int *pnCol /* OUT: Number of entries in output array */
-);
-
-/*
-** CAPI3REF: Obtain old.* Values From A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** The pIter argument passed to this function may either be an iterator
-** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
-** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
-** Furthermore, it may only be called if the type of change that the iterator
-** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
-** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
-**
-** Argument iVal must be greater than or equal to 0, and less than the number
-** of columns in the table affected by the current change. Otherwise,
-** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
-**
-** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of
-** original row values stored as part of the UPDATE or DELETE change and
-** returns SQLITE_OK. The name of the function comes from the fact that this
-** is similar to the "old.*" columns available to update or delete triggers.
-**
-** If some other error occurs (e.g. an OOM condition), an SQLite error code
-** is returned and *ppValue is set to NULL.
-*/
-SQLITE_API int sqlite3changeset_old(
- sqlite3_changeset_iter *pIter, /* Changeset iterator */
- int iVal, /* Column number */
- sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
-);
-
-/*
-** CAPI3REF: Obtain new.* Values From A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** The pIter argument passed to this function may either be an iterator
-** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
-** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
-** Furthermore, it may only be called if the type of change that the iterator
-** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
-** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
-**
-** Argument iVal must be greater than or equal to 0, and less than the number
-** of columns in the table affected by the current change. Otherwise,
-** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
-**
-** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of
-** new row values stored as part of the UPDATE or INSERT change and
-** returns SQLITE_OK. If the change is an UPDATE and does not include
-** a new value for the requested column, *ppValue is set to NULL and
-** SQLITE_OK returned. The name of the function comes from the fact that
-** this is similar to the "new.*" columns available to update or delete
-** triggers.
-**
-** If some other error occurs (e.g. an OOM condition), an SQLite error code
-** is returned and *ppValue is set to NULL.
-*/
-SQLITE_API int sqlite3changeset_new(
- sqlite3_changeset_iter *pIter, /* Changeset iterator */
- int iVal, /* Column number */
- sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
-);
-
-/*
-** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** This function should only be used with iterator objects passed to a
-** conflict-handler callback by [sqlite3changeset_apply()] with either
-** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
-** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
-** is set to NULL.
-**
-** Argument iVal must be greater than or equal to 0, and less than the number
-** of columns in the table affected by the current change. Otherwise,
-** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
-**
-** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the
-** "conflicting row" associated with the current conflict-handler callback
-** and returns SQLITE_OK.
-**
-** If some other error occurs (e.g. an OOM condition), an SQLite error code
-** is returned and *ppValue is set to NULL.
-*/
-SQLITE_API int sqlite3changeset_conflict(
- sqlite3_changeset_iter *pIter, /* Changeset iterator */
- int iVal, /* Column number */
- sqlite3_value **ppValue /* OUT: Value from conflicting row */
-);
-
-/*
-** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
-** METHOD: sqlite3_changeset_iter
-**
-** This function may only be called with an iterator passed to an
-** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
-** it sets the output variable to the total number of known foreign key
-** violations in the destination database and returns SQLITE_OK.
-**
-** In all other cases this function returns SQLITE_MISUSE.
-*/
-SQLITE_API int sqlite3changeset_fk_conflicts(
- sqlite3_changeset_iter *pIter, /* Changeset iterator */
- int *pnOut /* OUT: Number of FK violations */
-);
-
-
-/*
-** CAPI3REF: Finalize A Changeset Iterator
-** METHOD: sqlite3_changeset_iter
-**
-** This function is used to finalize an iterator allocated with
-** [sqlite3changeset_start()].
-**
-** This function should only be called on iterators created using the
-** [sqlite3changeset_start()] function. If an application calls this
-** function with an iterator passed to a conflict-handler by
-** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
-** call has no effect.
-**
-** If an error was encountered within a call to an sqlite3changeset_xxx()
-** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
-** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
-** to that error is returned by this function. Otherwise, SQLITE_OK is
-** returned. This is to allow the following pattern (pseudo-code):
-**
-**
-** sqlite3changeset_start();
-** while( SQLITE_ROW==sqlite3changeset_next() ){
-** // Do something with change.
-** }
-** rc = sqlite3changeset_finalize();
-** if( rc!=SQLITE_OK ){
-** // An error has occurred
-** }
-**
-*/
-SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
-
-/*
-** CAPI3REF: Invert A Changeset
-**
-** This function is used to "invert" a changeset object. Applying an inverted
-** changeset to a database reverses the effects of applying the uninverted
-** changeset. Specifically:
-**
-**
-** - Each DELETE change is changed to an INSERT, and
-**
- Each INSERT change is changed to a DELETE, and
-**
- For each UPDATE change, the old.* and new.* values are exchanged.
-**
-**
-** This function does not change the order in which changes appear within
-** the changeset. It merely reverses the sense of each individual change.
-**
-** If successful, a pointer to a buffer containing the inverted changeset
-** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
-** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
-** zeroed and an SQLite error code returned.
-**
-** It is the responsibility of the caller to eventually call sqlite3_free()
-** on the *ppOut pointer to free the buffer allocation following a successful
-** call to this function.
-**
-** WARNING/TODO: This function currently assumes that the input is a valid
-** changeset. If it is not, the results are undefined.
-*/
-SQLITE_API int sqlite3changeset_invert(
- int nIn, const void *pIn, /* Input changeset */
- int *pnOut, void **ppOut /* OUT: Inverse of input */
-);
-
-/*
-** CAPI3REF: Concatenate Two Changeset Objects
-**
-** This function is used to concatenate two changesets, A and B, into a
-** single changeset. The result is a changeset equivalent to applying
-** changeset A followed by changeset B.
-**
-** This function combines the two input changesets using an
-** sqlite3_changegroup object. Calling it produces similar results as the
-** following code fragment:
-**
-**
-** sqlite3_changegroup *pGrp;
-** rc = sqlite3_changegroup_new(&pGrp);
-** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
-** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
-** if( rc==SQLITE_OK ){
-** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
-** }else{
-** *ppOut = 0;
-** *pnOut = 0;
-** }
-**
-**
-** Refer to the sqlite3_changegroup documentation below for details.
-*/
-SQLITE_API int sqlite3changeset_concat(
- int nA, /* Number of bytes in buffer pA */
- void *pA, /* Pointer to buffer containing changeset A */
- int nB, /* Number of bytes in buffer pB */
- void *pB, /* Pointer to buffer containing changeset B */
- int *pnOut, /* OUT: Number of bytes in output changeset */
- void **ppOut /* OUT: Buffer containing output changeset */
-);
-
-
-/*
-** CAPI3REF: Changegroup Handle
-**
-** A changegroup is an object used to combine two or more
-** [changesets] or [patchsets]
-*/
-typedef struct sqlite3_changegroup sqlite3_changegroup;
-
-/*
-** CAPI3REF: Create A New Changegroup Object
-** CONSTRUCTOR: sqlite3_changegroup
-**
-** An sqlite3_changegroup object is used to combine two or more changesets
-** (or patchsets) into a single changeset (or patchset). A single changegroup
-** object may combine changesets or patchsets, but not both. The output is
-** always in the same format as the input.
-**
-** If successful, this function returns SQLITE_OK and populates (*pp) with
-** a pointer to a new sqlite3_changegroup object before returning. The caller
-** should eventually free the returned object using a call to
-** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
-** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
-**
-** The usual usage pattern for an sqlite3_changegroup object is as follows:
-**
-**
-** - It is created using a call to sqlite3changegroup_new().
-**
-**
- Zero or more changesets (or patchsets) are added to the object
-** by calling sqlite3changegroup_add().
-**
-**
- The result of combining all input changesets together is obtained
-** by the application via a call to sqlite3changegroup_output().
-**
-**
- The object is deleted using a call to sqlite3changegroup_delete().
-**
-**
-** Any number of calls to add() and output() may be made between the calls to
-** new() and delete(), and in any order.
-**
-** As well as the regular sqlite3changegroup_add() and
-** sqlite3changegroup_output() functions, also available are the streaming
-** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
-*/
-SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
-
-/*
-** CAPI3REF: Add A Changeset To A Changegroup
-** METHOD: sqlite3_changegroup
-**
-** Add all changes within the changeset (or patchset) in buffer pData (size
-** nData bytes) to the changegroup.
-**
-** If the buffer contains a patchset, then all prior calls to this function
-** on the same changegroup object must also have specified patchsets. Or, if
-** the buffer contains a changeset, so must have the earlier calls to this
-** function. Otherwise, SQLITE_ERROR is returned and no changes are added
-** to the changegroup.
-**
-** Rows within the changeset and changegroup are identified by the values in
-** their PRIMARY KEY columns. A change in the changeset is considered to
-** apply to the same row as a change already present in the changegroup if
-** the two rows have the same primary key.
-**
-** Changes to rows that do not already appear in the changegroup are
-** simply copied into it. Or, if both the new changeset and the changegroup
-** contain changes that apply to a single row, the final contents of the
-** changegroup depends on the type of each change, as follows:
-**
-**
-** | Existing Change |
-** New Change |
-** Output Change
-** |
|---|
| INSERT | INSERT |
-** The new change is ignored. This case does not occur if the new
-** changeset was recorded immediately after the changesets already
-** added to the changegroup.
-** |
| INSERT | UPDATE |
-** The INSERT change remains in the changegroup. The values in the
-** INSERT change are modified as if the row was inserted by the
-** existing change and then updated according to the new change.
-** |
| INSERT | DELETE |
-** The existing INSERT is removed from the changegroup. The DELETE is
-** not added.
-** |
| UPDATE | INSERT |
-** The new change is ignored. This case does not occur if the new
-** changeset was recorded immediately after the changesets already
-** added to the changegroup.
-** |
| UPDATE | UPDATE |
-** The existing UPDATE remains within the changegroup. It is amended
-** so that the accompanying values are as if the row was updated once
-** by the existing change and then again by the new change.
-** |
| UPDATE | DELETE |
-** The existing UPDATE is replaced by the new DELETE within the
-** changegroup.
-** |
| DELETE | INSERT |
-** If one or more of the column values in the row inserted by the
-** new change differ from those in the row deleted by the existing
-** change, the existing DELETE is replaced by an UPDATE within the
-** changegroup. Otherwise, if the inserted row is exactly the same
-** as the deleted row, the existing DELETE is simply discarded.
-** |
| DELETE | UPDATE |
-** The new change is ignored. This case does not occur if the new
-** changeset was recorded immediately after the changesets already
-** added to the changegroup.
-** |
| DELETE | DELETE |
-** The new change is ignored. This case does not occur if the new
-** changeset was recorded immediately after the changesets already
-** added to the changegroup.
-** |
-**
-** If the new changeset contains changes to a table that is already present
-** in the changegroup, then the number of columns and the position of the
-** primary key columns for the table must be consistent. If this is not the
-** case, this function fails with SQLITE_SCHEMA. If the input changeset
-** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
-** returned. Or, if an out-of-memory condition occurs during processing, this
-** function returns SQLITE_NOMEM. In all cases, if an error occurs the
-** final contents of the changegroup is undefined.
-**
-** If no error occurs, SQLITE_OK is returned.
-*/
-SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
-
-/*
-** CAPI3REF: Obtain A Composite Changeset From A Changegroup
-** METHOD: sqlite3_changegroup
-**
-** Obtain a buffer containing a changeset (or patchset) representing the
-** current contents of the changegroup. If the inputs to the changegroup
-** were themselves changesets, the output is a changeset. Or, if the
-** inputs were patchsets, the output is also a patchset.
-**
-** As with the output of the sqlite3session_changeset() and
-** sqlite3session_patchset() functions, all changes related to a single
-** table are grouped together in the output of this function. Tables appear
-** in the same order as for the very first changeset added to the changegroup.
-** If the second or subsequent changesets added to the changegroup contain
-** changes for tables that do not appear in the first changeset, they are
-** appended onto the end of the output changeset, again in the order in
-** which they are first encountered.
-**
-** If an error occurs, an SQLite error code is returned and the output
-** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
-** is returned and the output variables are set to the size of and a
-** pointer to the output buffer, respectively. In this case it is the
-** responsibility of the caller to eventually free the buffer using a
-** call to sqlite3_free().
-*/
-SQLITE_API int sqlite3changegroup_output(
- sqlite3_changegroup*,
- int *pnData, /* OUT: Size of output buffer in bytes */
- void **ppData /* OUT: Pointer to output buffer */
-);
-
-/*
-** CAPI3REF: Delete A Changegroup Object
-** DESTRUCTOR: sqlite3_changegroup
-*/
-SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
-
-/*
-** CAPI3REF: Apply A Changeset To A Database
-**
-** Apply a changeset or patchset to a database. These functions attempt to
-** update the "main" database attached to handle db with the changes found in
-** the changeset passed via the second and third arguments.
-**
-** The fourth argument (xFilter) passed to these functions is the "filter
-** callback". If it is not NULL, then for each table affected by at least one
-** change in the changeset, the filter callback is invoked with
-** the table name as the second argument, and a copy of the context pointer
-** passed as the sixth argument as the first. If the "filter callback"
-** returns zero, then no attempt is made to apply any changes to the table.
-** Otherwise, if the return value is non-zero or the xFilter argument to
-** is NULL, all changes related to the table are attempted.
-**
-** For each table that is not excluded by the filter callback, this function
-** tests that the target database contains a compatible table. A table is
-** considered compatible if all of the following are true:
-**
-**
-** - The table has the same name as the name recorded in the
-** changeset, and
-**
- The table has at least as many columns as recorded in the
-** changeset, and
-**
- The table has primary key columns in the same position as
-** recorded in the changeset.
-**
-**
-** If there is no compatible table, it is not an error, but none of the
-** changes associated with the table are applied. A warning message is issued
-** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
-** one such warning is issued for each table in the changeset.
-**
-** For each change for which there is a compatible table, an attempt is made
-** to modify the table contents according to the UPDATE, INSERT or DELETE
-** change. If a change cannot be applied cleanly, the conflict handler
-** function passed as the fifth argument to sqlite3changeset_apply() may be
-** invoked. A description of exactly when the conflict handler is invoked for
-** each type of change is below.
-**
-** Unlike the xFilter argument, xConflict may not be passed NULL. The results
-** of passing anything other than a valid function pointer as the xConflict
-** argument are undefined.
-**
-** Each time the conflict handler function is invoked, it must return one
-** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
-** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
-** if the second argument passed to the conflict handler is either
-** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
-** returns an illegal value, any changes already made are rolled back and
-** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
-** actions are taken by sqlite3changeset_apply() depending on the value
-** returned by each invocation of the conflict-handler function. Refer to
-** the documentation for the three
-** [SQLITE_CHANGESET_OMIT|available return values] for details.
-**
-**
-** - DELETE Changes
-
-** For each DELETE change, the function checks if the target database
-** contains a row with the same primary key value (or values) as the
-** original row values stored in the changeset. If it does, and the values
-** stored in all non-primary key columns also match the values stored in
-** the changeset the row is deleted from the target database.
-**
-** If a row with matching primary key values is found, but one or more of
-** the non-primary key fields contains a value different from the original
-** row value stored in the changeset, the conflict-handler function is
-** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
-** database table has more columns than are recorded in the changeset,
-** only the values of those non-primary key fields are compared against
-** the current database contents - any trailing database table columns
-** are ignored.
-**
-** If no row with matching primary key values is found in the database,
-** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
-** passed as the second argument.
-**
-** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
-** (which can only happen if a foreign key constraint is violated), the
-** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
-** passed as the second argument. This includes the case where the DELETE
-** operation is attempted because an earlier call to the conflict handler
-** function returned [SQLITE_CHANGESET_REPLACE].
-**
-**
- INSERT Changes
-
-** For each INSERT change, an attempt is made to insert the new row into
-** the database. If the changeset row contains fewer fields than the
-** database table, the trailing fields are populated with their default
-** values.
-**
-** If the attempt to insert the row fails because the database already
-** contains a row with the same primary key values, the conflict handler
-** function is invoked with the second argument set to
-** [SQLITE_CHANGESET_CONFLICT].
-**
-** If the attempt to insert the row fails because of some other constraint
-** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
-** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
-** This includes the case where the INSERT operation is re-attempted because
-** an earlier call to the conflict handler function returned
-** [SQLITE_CHANGESET_REPLACE].
-**
-**
- UPDATE Changes
-
-** For each UPDATE change, the function checks if the target database
-** contains a row with the same primary key value (or values) as the
-** original row values stored in the changeset. If it does, and the values
-** stored in all modified non-primary key columns also match the values
-** stored in the changeset the row is updated within the target database.
-**
-** If a row with matching primary key values is found, but one or more of
-** the modified non-primary key fields contains a value different from an
-** original row value stored in the changeset, the conflict-handler function
-** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
-** UPDATE changes only contain values for non-primary key fields that are
-** to be modified, only those fields need to match the original values to
-** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
-**
-** If no row with matching primary key values is found in the database,
-** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
-** passed as the second argument.
-**
-** If the UPDATE operation is attempted, but SQLite returns
-** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
-** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
-** This includes the case where the UPDATE operation is attempted after
-** an earlier call to the conflict handler function returned
-** [SQLITE_CHANGESET_REPLACE].
-**
-**
-** It is safe to execute SQL statements, including those that write to the
-** table that the callback related to, from within the xConflict callback.
-** This can be used to further customize the applications conflict
-** resolution strategy.
-**
-** All changes made by these functions are enclosed in a savepoint transaction.
-** If any other error (aside from a constraint failure when attempting to
-** write to the target database) occurs, then the savepoint transaction is
-** rolled back, restoring the target database to its original state, and an
-** SQLite error code returned.
-**
-** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
-** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
-** may set (*ppRebase) to point to a "rebase" that may be used with the
-** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
-** is set to the size of the buffer in bytes. It is the responsibility of the
-** caller to eventually free any such buffer using sqlite3_free(). The buffer
-** is only allocated and populated if one or more conflicts were encountered
-** while applying the patchset. See comments surrounding the sqlite3_rebaser
-** APIs for further details.
-**
-** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
-** may be modified by passing a combination of
-** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
-**
-** Note that the sqlite3changeset_apply_v2() API is still experimental
-** and therefore subject to change.
-*/
-SQLITE_API int sqlite3changeset_apply(
- sqlite3 *db, /* Apply change to "main" db of this handle */
- int nChangeset, /* Size of changeset in bytes */
- void *pChangeset, /* Changeset blob */
- int(*xFilter)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- const char *zTab /* Table name */
- ),
- int(*xConflict)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
- sqlite3_changeset_iter *p /* Handle describing change and conflict */
- ),
- void *pCtx /* First argument passed to xConflict */
-);
-SQLITE_API int sqlite3changeset_apply_v2(
- sqlite3 *db, /* Apply change to "main" db of this handle */
- int nChangeset, /* Size of changeset in bytes */
- void *pChangeset, /* Changeset blob */
- int(*xFilter)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- const char *zTab /* Table name */
- ),
- int(*xConflict)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
- sqlite3_changeset_iter *p /* Handle describing change and conflict */
- ),
- void *pCtx, /* First argument passed to xConflict */
- void **ppRebase, int *pnRebase, /* OUT: Rebase data */
- int flags /* SESSION_CHANGESETAPPLY_* flags */
-);
-
-/*
-** CAPI3REF: Flags for sqlite3changeset_apply_v2
-**
-** The following flags may passed via the 9th parameter to
-** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
-**
-**
-** - SQLITE_CHANGESETAPPLY_NOSAVEPOINT
-
-** Usually, the sessions module encloses all operations performed by
-** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
-** SAVEPOINT is committed if the changeset or patchset is successfully
-** applied, or rolled back if an error occurs. Specifying this flag
-** causes the sessions module to omit this savepoint. In this case, if the
-** caller has an open transaction or savepoint when apply_v2() is called,
-** it may revert the partially applied changeset by rolling it back.
-**
-**
- SQLITE_CHANGESETAPPLY_INVERT
-
-** Invert the changeset before applying it. This is equivalent to inverting
-** a changeset using sqlite3changeset_invert() before applying it. It is
-** an error to specify this flag with a patchset.
-*/
-#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
-#define SQLITE_CHANGESETAPPLY_INVERT 0x0002
-
-/*
-** CAPI3REF: Constants Passed To The Conflict Handler
-**
-** Values that may be passed as the second argument to a conflict-handler.
-**
-**
-** - SQLITE_CHANGESET_DATA
-
-** The conflict handler is invoked with CHANGESET_DATA as the second argument
-** when processing a DELETE or UPDATE change if a row with the required
-** PRIMARY KEY fields is present in the database, but one or more other
-** (non primary-key) fields modified by the update do not contain the
-** expected "before" values.
-**
-** The conflicting row, in this case, is the database row with the matching
-** primary key.
-**
-**
- SQLITE_CHANGESET_NOTFOUND
-
-** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
-** argument when processing a DELETE or UPDATE change if a row with the
-** required PRIMARY KEY fields is not present in the database.
-**
-** There is no conflicting row in this case. The results of invoking the
-** sqlite3changeset_conflict() API are undefined.
-**
-**
- SQLITE_CHANGESET_CONFLICT
-
-** CHANGESET_CONFLICT is passed as the second argument to the conflict
-** handler while processing an INSERT change if the operation would result
-** in duplicate primary key values.
-**
-** The conflicting row in this case is the database row with the matching
-** primary key.
-**
-**
- SQLITE_CHANGESET_FOREIGN_KEY
-
-** If foreign key handling is enabled, and applying a changeset leaves the
-** database in a state containing foreign key violations, the conflict
-** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
-** exactly once before the changeset is committed. If the conflict handler
-** returns CHANGESET_OMIT, the changes, including those that caused the
-** foreign key constraint violation, are committed. Or, if it returns
-** CHANGESET_ABORT, the changeset is rolled back.
-**
-** No current or conflicting row information is provided. The only function
-** it is possible to call on the supplied sqlite3_changeset_iter handle
-** is sqlite3changeset_fk_conflicts().
-**
-**
- SQLITE_CHANGESET_CONSTRAINT
-
-** If any other constraint violation occurs while applying a change (i.e.
-** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
-** invoked with CHANGESET_CONSTRAINT as the second argument.
-**
-** There is no conflicting row in this case. The results of invoking the
-** sqlite3changeset_conflict() API are undefined.
-**
-**
-*/
-#define SQLITE_CHANGESET_DATA 1
-#define SQLITE_CHANGESET_NOTFOUND 2
-#define SQLITE_CHANGESET_CONFLICT 3
-#define SQLITE_CHANGESET_CONSTRAINT 4
-#define SQLITE_CHANGESET_FOREIGN_KEY 5
-
-/*
-** CAPI3REF: Constants Returned By The Conflict Handler
-**
-** A conflict handler callback must return one of the following three values.
-**
-**
-** - SQLITE_CHANGESET_OMIT
-
-** If a conflict handler returns this value no special action is taken. The
-** change that caused the conflict is not applied. The session module
-** continues to the next change in the changeset.
-**
-**
- SQLITE_CHANGESET_REPLACE
-
-** This value may only be returned if the second argument to the conflict
-** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
-** is not the case, any changes applied so far are rolled back and the
-** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
-**
-** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
-** handler, then the conflicting row is either updated or deleted, depending
-** on the type of change.
-**
-** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
-** handler, then the conflicting row is removed from the database and a
-** second attempt to apply the change is made. If this second attempt fails,
-** the original row is restored to the database before continuing.
-**
-**
- SQLITE_CHANGESET_ABORT
-
-** If this value is returned, any changes applied so far are rolled back
-** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
-**
-*/
-#define SQLITE_CHANGESET_OMIT 0
-#define SQLITE_CHANGESET_REPLACE 1
-#define SQLITE_CHANGESET_ABORT 2
-
-/*
-** CAPI3REF: Rebasing changesets
-** EXPERIMENTAL
-**
-** Suppose there is a site hosting a database in state S0. And that
-** modifications are made that move that database to state S1 and a
-** changeset recorded (the "local" changeset). Then, a changeset based
-** on S0 is received from another site (the "remote" changeset) and
-** applied to the database. The database is then in state
-** (S1+"remote"), where the exact state depends on any conflict
-** resolution decisions (OMIT or REPLACE) made while applying "remote".
-** Rebasing a changeset is to update it to take those conflict
-** resolution decisions into account, so that the same conflicts
-** do not have to be resolved elsewhere in the network.
-**
-** For example, if both the local and remote changesets contain an
-** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
-**
-** local: INSERT INTO t1 VALUES(1, 'v1');
-** remote: INSERT INTO t1 VALUES(1, 'v2');
-**
-** and the conflict resolution is REPLACE, then the INSERT change is
-** removed from the local changeset (it was overridden). Or, if the
-** conflict resolution was "OMIT", then the local changeset is modified
-** to instead contain:
-**
-** UPDATE t1 SET b = 'v2' WHERE a=1;
-**
-** Changes within the local changeset are rebased as follows:
-**
-**
-** - Local INSERT
-
-** This may only conflict with a remote INSERT. If the conflict
-** resolution was OMIT, then add an UPDATE change to the rebased
-** changeset. Or, if the conflict resolution was REPLACE, add
-** nothing to the rebased changeset.
-**
-**
- Local DELETE
-
-** This may conflict with a remote UPDATE or DELETE. In both cases the
-** only possible resolution is OMIT. If the remote operation was a
-** DELETE, then add no change to the rebased changeset. If the remote
-** operation was an UPDATE, then the old.* fields of change are updated
-** to reflect the new.* values in the UPDATE.
-**
-**
- Local UPDATE
-
-** This may conflict with a remote UPDATE or DELETE. If it conflicts
-** with a DELETE, and the conflict resolution was OMIT, then the update
-** is changed into an INSERT. Any undefined values in the new.* record
-** from the update change are filled in using the old.* values from
-** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
-** the UPDATE change is simply omitted from the rebased changeset.
-**
-** If conflict is with a remote UPDATE and the resolution is OMIT, then
-** the old.* values are rebased using the new.* values in the remote
-** change. Or, if the resolution is REPLACE, then the change is copied
-** into the rebased changeset with updates to columns also updated by
-** the conflicting remote UPDATE removed. If this means no columns would
-** be updated, the change is omitted.
-**
-**
-** A local change may be rebased against multiple remote changes
-** simultaneously. If a single key is modified by multiple remote
-** changesets, they are combined as follows before the local changeset
-** is rebased:
-**
-**
-** - If there has been one or more REPLACE resolutions on a
-** key, it is rebased according to a REPLACE.
-**
-**
- If there have been no REPLACE resolutions on a key, then
-** the local changeset is rebased according to the most recent
-** of the OMIT resolutions.
-**
-**
-** Note that conflict resolutions from multiple remote changesets are
-** combined on a per-field basis, not per-row. This means that in the
-** case of multiple remote UPDATE operations, some fields of a single
-** local change may be rebased for REPLACE while others are rebased for
-** OMIT.
-**
-** In order to rebase a local changeset, the remote changeset must first
-** be applied to the local database using sqlite3changeset_apply_v2() and
-** the buffer of rebase information captured. Then:
-**
-**
-** - An sqlite3_rebaser object is created by calling
-** sqlite3rebaser_create().
-**
- The new object is configured with the rebase buffer obtained from
-** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
-** If the local changeset is to be rebased against multiple remote
-** changesets, then sqlite3rebaser_configure() should be called
-** multiple times, in the same order that the multiple
-** sqlite3changeset_apply_v2() calls were made.
-**
- Each local changeset is rebased by calling sqlite3rebaser_rebase().
-**
- The sqlite3_rebaser object is deleted by calling
-** sqlite3rebaser_delete().
-**
-*/
-typedef struct sqlite3_rebaser sqlite3_rebaser;
-
-/*
-** CAPI3REF: Create a changeset rebaser object.
-** EXPERIMENTAL
-**
-** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
-** point to the new object and return SQLITE_OK. Otherwise, if an error
-** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
-** to NULL.
-*/
-SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
-
-/*
-** CAPI3REF: Configure a changeset rebaser object.
-** EXPERIMENTAL
-**
-** Configure the changeset rebaser object to rebase changesets according
-** to the conflict resolutions described by buffer pRebase (size nRebase
-** bytes), which must have been obtained from a previous call to
-** sqlite3changeset_apply_v2().
-*/
-SQLITE_API int sqlite3rebaser_configure(
- sqlite3_rebaser*,
- int nRebase, const void *pRebase
-);
-
-/*
-** CAPI3REF: Rebase a changeset
-** EXPERIMENTAL
-**
-** Argument pIn must point to a buffer containing a changeset nIn bytes
-** in size. This function allocates and populates a buffer with a copy
-** of the changeset rebased rebased according to the configuration of the
-** rebaser object passed as the first argument. If successful, (*ppOut)
-** is set to point to the new buffer containing the rebased changeset and
-** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
-** responsibility of the caller to eventually free the new buffer using
-** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
-** are set to zero and an SQLite error code returned.
-*/
-SQLITE_API int sqlite3rebaser_rebase(
- sqlite3_rebaser*,
- int nIn, const void *pIn,
- int *pnOut, void **ppOut
-);
-
-/*
-** CAPI3REF: Delete a changeset rebaser object.
-** EXPERIMENTAL
-**
-** Delete the changeset rebaser object and all associated resources. There
-** should be one call to this function for each successful invocation
-** of sqlite3rebaser_create().
-*/
-SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
-
-/*
-** CAPI3REF: Streaming Versions of API functions.
-**
-** The six streaming API xxx_strm() functions serve similar purposes to the
-** corresponding non-streaming API functions:
-**
-**
-** | Streaming function | Non-streaming equivalent |
-**
|---|
| sqlite3changeset_apply_strm | [sqlite3changeset_apply]
-** |
| sqlite3changeset_apply_strm_v2 | [sqlite3changeset_apply_v2]
-** |
| sqlite3changeset_concat_strm | [sqlite3changeset_concat]
-** |
| sqlite3changeset_invert_strm | [sqlite3changeset_invert]
-** |
| sqlite3changeset_start_strm | [sqlite3changeset_start]
-** |
| sqlite3session_changeset_strm | [sqlite3session_changeset]
-** |
| sqlite3session_patchset_strm | [sqlite3session_patchset]
-** |
-**
-** Non-streaming functions that accept changesets (or patchsets) as input
-** require that the entire changeset be stored in a single buffer in memory.
-** Similarly, those that return a changeset or patchset do so by returning
-** a pointer to a single large buffer allocated using sqlite3_malloc().
-** Normally this is convenient. However, if an application running in a
-** low-memory environment is required to handle very large changesets, the
-** large contiguous memory allocations required can become onerous.
-**
-** In order to avoid this problem, instead of a single large buffer, input
-** is passed to a streaming API functions by way of a callback function that
-** the sessions module invokes to incrementally request input data as it is
-** required. In all cases, a pair of API function parameters such as
-**
-**
-** int nChangeset,
-** void *pChangeset,
-**
-**
-** Is replaced by:
-**
-**
-** int (*xInput)(void *pIn, void *pData, int *pnData),
-** void *pIn,
-**
-**
-** Each time the xInput callback is invoked by the sessions module, the first
-** argument passed is a copy of the supplied pIn context pointer. The second
-** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
-** error occurs the xInput method should copy up to (*pnData) bytes of data
-** into the buffer and set (*pnData) to the actual number of bytes copied
-** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
-** should be set to zero to indicate this. Or, if an error occurs, an SQLite
-** error code should be returned. In all cases, if an xInput callback returns
-** an error, all processing is abandoned and the streaming API function
-** returns a copy of the error code to the caller.
-**
-** In the case of sqlite3changeset_start_strm(), the xInput callback may be
-** invoked by the sessions module at any point during the lifetime of the
-** iterator. If such an xInput callback returns an error, the iterator enters
-** an error state, whereby all subsequent calls to iterator functions
-** immediately fail with the same error code as returned by xInput.
-**
-** Similarly, streaming API functions that return changesets (or patchsets)
-** return them in chunks by way of a callback function instead of via a
-** pointer to a single large buffer. In this case, a pair of parameters such
-** as:
-**
-**
-** int *pnChangeset,
-** void **ppChangeset,
-**
-**
-** Is replaced by:
-**
-**
-** int (*xOutput)(void *pOut, const void *pData, int nData),
-** void *pOut
-**
-**
-** The xOutput callback is invoked zero or more times to return data to
-** the application. The first parameter passed to each call is a copy of the
-** pOut pointer supplied by the application. The second parameter, pData,
-** points to a buffer nData bytes in size containing the chunk of output
-** data being returned. If the xOutput callback successfully processes the
-** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
-** it should return some other SQLite error code. In this case processing
-** is immediately abandoned and the streaming API function returns a copy
-** of the xOutput error code to the application.
-**
-** The sessions module never invokes an xOutput callback with the third
-** parameter set to a value less than or equal to zero. Other than this,
-** no guarantees are made as to the size of the chunks of data returned.
-*/
-SQLITE_API int sqlite3changeset_apply_strm(
- sqlite3 *db, /* Apply change to "main" db of this handle */
- int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
- void *pIn, /* First arg for xInput */
- int(*xFilter)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- const char *zTab /* Table name */
- ),
- int(*xConflict)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
- sqlite3_changeset_iter *p /* Handle describing change and conflict */
- ),
- void *pCtx /* First argument passed to xConflict */
-);
-SQLITE_API int sqlite3changeset_apply_v2_strm(
- sqlite3 *db, /* Apply change to "main" db of this handle */
- int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
- void *pIn, /* First arg for xInput */
- int(*xFilter)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- const char *zTab /* Table name */
- ),
- int(*xConflict)(
- void *pCtx, /* Copy of sixth arg to _apply() */
- int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
- sqlite3_changeset_iter *p /* Handle describing change and conflict */
- ),
- void *pCtx, /* First argument passed to xConflict */
- void **ppRebase, int *pnRebase,
- int flags
-);
-SQLITE_API int sqlite3changeset_concat_strm(
- int (*xInputA)(void *pIn, void *pData, int *pnData),
- void *pInA,
- int (*xInputB)(void *pIn, void *pData, int *pnData),
- void *pInB,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-SQLITE_API int sqlite3changeset_invert_strm(
- int (*xInput)(void *pIn, void *pData, int *pnData),
- void *pIn,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-SQLITE_API int sqlite3changeset_start_strm(
- sqlite3_changeset_iter **pp,
- int (*xInput)(void *pIn, void *pData, int *pnData),
- void *pIn
-);
-SQLITE_API int sqlite3changeset_start_v2_strm(
- sqlite3_changeset_iter **pp,
- int (*xInput)(void *pIn, void *pData, int *pnData),
- void *pIn,
- int flags
-);
-SQLITE_API int sqlite3session_changeset_strm(
- sqlite3_session *pSession,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-SQLITE_API int sqlite3session_patchset_strm(
- sqlite3_session *pSession,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
- int (*xInput)(void *pIn, void *pData, int *pnData),
- void *pIn
-);
-SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-SQLITE_API int sqlite3rebaser_rebase_strm(
- sqlite3_rebaser *pRebaser,
- int (*xInput)(void *pIn, void *pData, int *pnData),
- void *pIn,
- int (*xOutput)(void *pOut, const void *pData, int nData),
- void *pOut
-);
-
-/*
-** CAPI3REF: Configure global parameters
-**
-** The sqlite3session_config() interface is used to make global configuration
-** changes to the sessions module in order to tune it to the specific needs
-** of the application.
-**
-** The sqlite3session_config() interface is not threadsafe. If it is invoked
-** while any other thread is inside any other sessions method then the
-** results are undefined. Furthermore, if it is invoked after any sessions
-** related objects have been created, the results are also undefined.
-**
-** The first argument to the sqlite3session_config() function must be one
-** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
-** interpretation of the (void*) value passed as the second parameter and
-** the effect of calling this function depends on the value of the first
-** parameter.
-**
-**
-** - SQLITE_SESSION_CONFIG_STRMSIZE
-
-** By default, the sessions module streaming interfaces attempt to input
-** and output data in approximately 1 KiB chunks. This operand may be used
-** to set and query the value of this configuration setting. The pointer
-** passed as the second argument must point to a value of type (int).
-** If this value is greater than 0, it is used as the new streaming data
-** chunk size for both input and output. Before returning, the (int) value
-** pointed to by pArg is set to the final value of the streaming interface
-** chunk size.
-**
-**
-** This function returns SQLITE_OK if successful, or an SQLite error code
-** otherwise.
-*/
-SQLITE_API int sqlite3session_config(int op, void *pArg);
-
-/*
-** CAPI3REF: Values for sqlite3session_config().
-*/
-#define SQLITE_SESSION_CONFIG_STRMSIZE 1
-
-/*
-** Make sure we can call this stuff from C++.
-*/
-#if 0
-}
-#endif
-
-#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
-
-/******** End of sqlite3session.h *********/
-/******** Begin file fts5.h *********/
-/*
-** 2014 May 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.
-**
-******************************************************************************
-**
-** Interfaces to extend FTS5. Using the interfaces defined in this file,
-** FTS5 may be extended with:
-**
-** * custom tokenizers, and
-** * custom auxiliary functions.
-*/
-
-
-#ifndef _FTS5_H
-#define _FTS5_H
-
-
-#if 0
-extern "C" {
-#endif
-
-/*************************************************************************
-** CUSTOM AUXILIARY FUNCTIONS
-**
-** Virtual table implementations may overload SQL functions by implementing
-** the sqlite3_module.xFindFunction() method.
-*/
-
-typedef struct Fts5ExtensionApi Fts5ExtensionApi;
-typedef struct Fts5Context Fts5Context;
-typedef struct Fts5PhraseIter Fts5PhraseIter;
-
-typedef void (*fts5_extension_function)(
- const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
- Fts5Context *pFts, /* First arg to pass to pApi functions */
- sqlite3_context *pCtx, /* Context for returning result/error */
- int nVal, /* Number of values in apVal[] array */
- sqlite3_value **apVal /* Array of trailing arguments */
-);
-
-struct Fts5PhraseIter {
- const unsigned char *a;
- const unsigned char *b;
-};
-
-/*
-** EXTENSION API FUNCTIONS
-**
-** xUserData(pFts):
-** Return a copy of the context pointer the extension function was
-** registered with.
-**
-** xColumnTotalSize(pFts, iCol, pnToken):
-** If parameter iCol is less than zero, set output variable *pnToken
-** to the total number of tokens in the FTS5 table. Or, if iCol is
-** non-negative but less than the number of columns in the table, return
-** the total number of tokens in column iCol, considering all rows in
-** the FTS5 table.
-**
-** If parameter iCol is greater than or equal to the number of columns
-** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-** an OOM condition or IO error), an appropriate SQLite error code is
-** returned.
-**
-** xColumnCount(pFts):
-** Return the number of columns in the table.
-**
-** xColumnSize(pFts, iCol, pnToken):
-** If parameter iCol is less than zero, set output variable *pnToken
-** to the total number of tokens in the current row. Or, if iCol is
-** non-negative but less than the number of columns in the table, set
-** *pnToken to the number of tokens in column iCol of the current row.
-**
-** If parameter iCol is greater than or equal to the number of columns
-** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-** an OOM condition or IO error), an appropriate SQLite error code is
-** returned.
-**
-** This function may be quite inefficient if used with an FTS5 table
-** created with the "columnsize=0" option.
-**
-** xColumnText:
-** This function attempts to retrieve the text of column iCol of the
-** current document. If successful, (*pz) is set to point to a buffer
-** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
-** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
-** if an error occurs, an SQLite error code is returned and the final values
-** of (*pz) and (*pn) are undefined.
-**
-** xPhraseCount:
-** Returns the number of phrases in the current query expression.
-**
-** xPhraseSize:
-** Returns the number of tokens in phrase iPhrase of the query. Phrases
-** are numbered starting from zero.
-**
-** xInstCount:
-** Set *pnInst to the total number of occurrences of all phrases within
-** the query within the current row. Return SQLITE_OK if successful, or
-** an error code (i.e. SQLITE_NOMEM) if an error occurs.
-**
-** This API can be quite slow if used with an FTS5 table created with the
-** "detail=none" or "detail=column" option. If the FTS5 table is created
-** with either "detail=none" or "detail=column" and "content=" option
-** (i.e. if it is a contentless table), then this API always returns 0.
-**
-** xInst:
-** Query for the details of phrase match iIdx within the current row.
-** Phrase matches are numbered starting from zero, so the iIdx argument
-** should be greater than or equal to zero and smaller than the value
-** output by xInstCount().
-**
-** Usually, output parameter *piPhrase is set to the phrase number, *piCol
-** to the column in which it occurs and *piOff the token offset of the
-** first token of the phrase. Returns SQLITE_OK if successful, or an error
-** code (i.e. SQLITE_NOMEM) if an error occurs.
-**
-** This API can be quite slow if used with an FTS5 table created with the
-** "detail=none" or "detail=column" option.
-**
-** xRowid:
-** Returns the rowid of the current row.
-**
-** xTokenize:
-** Tokenize text using the tokenizer belonging to the FTS5 table.
-**
-** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
-** This API function is used to query the FTS table for phrase iPhrase
-** of the current query. Specifically, a query equivalent to:
-**
-** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
-**
-** with $p set to a phrase equivalent to the phrase iPhrase of the
-** current query is executed. Any column filter that applies to
-** phrase iPhrase of the current query is included in $p. For each
-** row visited, the callback function passed as the fourth argument
-** is invoked. The context and API objects passed to the callback
-** function may be used to access the properties of each matched row.
-** Invoking Api.xUserData() returns a copy of the pointer passed as
-** the third argument to pUserData.
-**
-** If the callback function returns any value other than SQLITE_OK, the
-** query is abandoned and the xQueryPhrase function returns immediately.
-** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
-** Otherwise, the error code is propagated upwards.
-**
-** If the query runs to completion without incident, SQLITE_OK is returned.
-** Or, if some error occurs before the query completes or is aborted by
-** the callback, an SQLite error code is returned.
-**
-**
-** xSetAuxdata(pFts5, pAux, xDelete)
-**
-** Save the pointer passed as the second argument as the extension functions
-** "auxiliary data". The pointer may then be retrieved by the current or any
-** future invocation of the same fts5 extension function made as part of
-** the same MATCH query using the xGetAuxdata() API.
-**
-** Each extension function is allocated a single auxiliary data slot for
-** each FTS query (MATCH expression). If the extension function is invoked
-** more than once for a single FTS query, then all invocations share a
-** single auxiliary data context.
-**
-** If there is already an auxiliary data pointer when this function is
-** invoked, then it is replaced by the new pointer. If an xDelete callback
-** was specified along with the original pointer, it is invoked at this
-** point.
-**
-** The xDelete callback, if one is specified, is also invoked on the
-** auxiliary data pointer after the FTS5 query has finished.
-**
-** If an error (e.g. an OOM condition) occurs within this function,
-** the auxiliary data is set to NULL and an error code returned. If the
-** xDelete parameter was not NULL, it is invoked on the auxiliary data
-** pointer before returning.
-**
-**
-** xGetAuxdata(pFts5, bClear)
-**
-** Returns the current auxiliary data pointer for the fts5 extension
-** function. See the xSetAuxdata() method for details.
-**
-** If the bClear argument is non-zero, then the auxiliary data is cleared
-** (set to NULL) before this function returns. In this case the xDelete,
-** if any, is not invoked.
-**
-**
-** xRowCount(pFts5, pnRow)
-**
-** This function is used to retrieve the total number of rows in the table.
-** In other words, the same value that would be returned by:
-**
-** SELECT count(*) FROM ftstable;
-**
-** xPhraseFirst()
-** This function is used, along with type Fts5PhraseIter and the xPhraseNext
-** method, to iterate through all instances of a single query phrase within
-** the current row. This is the same information as is accessible via the
-** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
-** to use, this API may be faster under some circumstances. To iterate
-** through instances of phrase iPhrase, use the following code:
-**
-** Fts5PhraseIter iter;
-** int iCol, iOff;
-** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
-** iCol>=0;
-** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
-** ){
-** // An instance of phrase iPhrase at offset iOff of column iCol
-** }
-**
-** The Fts5PhraseIter structure is defined above. Applications should not
-** modify this structure directly - it should only be used as shown above
-** with the xPhraseFirst() and xPhraseNext() API methods (and by
-** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
-**
-** This API can be quite slow if used with an FTS5 table created with the
-** "detail=none" or "detail=column" option. If the FTS5 table is created
-** with either "detail=none" or "detail=column" and "content=" option
-** (i.e. if it is a contentless table), then this API always iterates
-** through an empty set (all calls to xPhraseFirst() set iCol to -1).
-**
-** xPhraseNext()
-** See xPhraseFirst above.
-**
-** xPhraseFirstColumn()
-** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
-** and xPhraseNext() APIs described above. The difference is that instead
-** of iterating through all instances of a phrase in the current row, these
-** APIs are used to iterate through the set of columns in the current row
-** that contain one or more instances of a specified phrase. For example:
-**
-** Fts5PhraseIter iter;
-** int iCol;
-** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
-** iCol>=0;
-** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
-** ){
-** // Column iCol contains at least one instance of phrase iPhrase
-** }
-**
-** This API can be quite slow if used with an FTS5 table created with the
-** "detail=none" option. If the FTS5 table is created with either
-** "detail=none" "content=" option (i.e. if it is a contentless table),
-** then this API always iterates through an empty set (all calls to
-** xPhraseFirstColumn() set iCol to -1).
-**
-** The information accessed using this API and its companion
-** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
-** (or xInst/xInstCount). The chief advantage of this API is that it is
-** significantly more efficient than those alternatives when used with
-** "detail=column" tables.
-**
-** xPhraseNextColumn()
-** See xPhraseFirstColumn above.
-*/
-struct Fts5ExtensionApi {
- int iVersion; /* Currently always set to 3 */
-
- void *(*xUserData)(Fts5Context*);
-
- int (*xColumnCount)(Fts5Context*);
- int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
- int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
-
- int (*xTokenize)(Fts5Context*,
- const char *pText, int nText, /* Text to tokenize */
- void *pCtx, /* Context passed to xToken() */
- int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
- );
-
- int (*xPhraseCount)(Fts5Context*);
- int (*xPhraseSize)(Fts5Context*, int iPhrase);
-
- int (*xInstCount)(Fts5Context*, int *pnInst);
- int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
-
- sqlite3_int64 (*xRowid)(Fts5Context*);
- int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
- int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
-
- int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
- int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
- );
- int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
- void *(*xGetAuxdata)(Fts5Context*, int bClear);
-
- int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
- void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
-
- int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
- void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
-};
-
-/*
-** CUSTOM AUXILIARY FUNCTIONS
-*************************************************************************/
-
-/*************************************************************************
-** CUSTOM TOKENIZERS
-**
-** Applications may also register custom tokenizer types. A tokenizer
-** is registered by providing fts5 with a populated instance of the
-** following structure. All structure methods must be defined, setting
-** any member of the fts5_tokenizer struct to NULL leads to undefined
-** behaviour. The structure methods are expected to function as follows:
-**
-** xCreate:
-** This function is used to allocate and initialize a tokenizer instance.
-** A tokenizer instance is required to actually tokenize text.
-**
-** The first argument passed to this function is a copy of the (void*)
-** pointer provided by the application when the fts5_tokenizer object
-** was registered with FTS5 (the third argument to xCreateTokenizer()).
-** The second and third arguments are an array of nul-terminated strings
-** containing the tokenizer arguments, if any, specified following the
-** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
-** to create the FTS5 table.
-**
-** The final argument is an output variable. If successful, (*ppOut)
-** should be set to point to the new tokenizer handle and SQLITE_OK
-** returned. If an error occurs, some value other than SQLITE_OK should
-** be returned. In this case, fts5 assumes that the final value of *ppOut
-** is undefined.
-**
-** xDelete:
-** This function is invoked to delete a tokenizer handle previously
-** allocated using xCreate(). Fts5 guarantees that this function will
-** be invoked exactly once for each successful call to xCreate().
-**
-** xTokenize:
-** This function is expected to tokenize the nText byte string indicated
-** by argument pText. pText may or may not be nul-terminated. The first
-** argument passed to this function is a pointer to an Fts5Tokenizer object
-** returned by an earlier call to xCreate().
-**
-** The second argument indicates the reason that FTS5 is requesting
-** tokenization of the supplied text. This is always one of the following
-** four values:
-**
-** - FTS5_TOKENIZE_DOCUMENT - A document is being inserted into
-** or removed from the FTS table. The tokenizer is being invoked to
-** determine the set of tokens to add to (or delete from) the
-** FTS index.
-**
-**
- FTS5_TOKENIZE_QUERY - A MATCH query is being executed
-** against the FTS index. The tokenizer is being called to tokenize
-** a bareword or quoted string specified as part of the query.
-**
-**
- (FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX) - Same as
-** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
-** followed by a "*" character, indicating that the last token
-** returned by the tokenizer will be treated as a token prefix.
-**
-**
- FTS5_TOKENIZE_AUX - The tokenizer is being invoked to
-** satisfy an fts5_api.xTokenize() request made by an auxiliary
-** function. Or an fts5_api.xColumnSize() request made by the same
-** on a columnsize=0 database.
-**
-**
-** For each token in the input string, the supplied callback xToken() must
-** be invoked. The first argument to it should be a copy of the pointer
-** passed as the second argument to xTokenize(). The third and fourth
-** arguments are a pointer to a buffer containing the token text, and the
-** size of the token in bytes. The 4th and 5th arguments are the byte offsets
-** of the first byte of and first byte immediately following the text from
-** which the token is derived within the input.
-**
-** The second argument passed to the xToken() callback ("tflags") should
-** normally be set to 0. The exception is if the tokenizer supports
-** synonyms. In this case see the discussion below for details.
-**
-** FTS5 assumes the xToken() callback is invoked for each token in the
-** order that they occur within the input text.
-**
-** If an xToken() callback returns any value other than SQLITE_OK, then
-** the tokenization should be abandoned and the xTokenize() method should
-** immediately return a copy of the xToken() return value. Or, if the
-** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
-** if an error occurs with the xTokenize() implementation itself, it
-** may abandon the tokenization and return any error code other than
-** SQLITE_OK or SQLITE_DONE.
-**
-** SYNONYM SUPPORT
-**
-** Custom tokenizers may also support synonyms. Consider a case in which a
-** user wishes to query for a phrase such as "first place". Using the
-** built-in tokenizers, the FTS5 query 'first + place' will match instances
-** of "first place" within the document set, but not alternative forms
-** such as "1st place". In some applications, it would be better to match
-** all instances of "first place" or "1st place" regardless of which form
-** the user specified in the MATCH query text.
-**
-** There are several ways to approach this in FTS5:
-**
-** - By mapping all synonyms to a single token. In this case, the
-** In the above example, this means that the tokenizer returns the
-** same token for inputs "first" and "1st". Say that token is in
-** fact "first", so that when the user inserts the document "I won
-** 1st place" entries are added to the index for tokens "i", "won",
-** "first" and "place". If the user then queries for '1st + place',
-** the tokenizer substitutes "first" for "1st" and the query works
-** as expected.
-**
-**
- By querying the index for all synonyms of each query term
-** separately. In this case, when tokenizing query text, the
-** tokenizer may provide multiple synonyms for a single term
-** within the document. FTS5 then queries the index for each
-** synonym individually. For example, faced with the query:
-**
-**
-** ... MATCH 'first place'
-**
-** the tokenizer offers both "1st" and "first" as synonyms for the
-** first token in the MATCH query and FTS5 effectively runs a query
-** similar to:
-**
-**
-** ... MATCH '(first OR 1st) place'
-**
-** except that, for the purposes of auxiliary functions, the query
-** still appears to contain just two phrases - "(first OR 1st)"
-** being treated as a single phrase.
-**
-**
- By adding multiple synonyms for a single term to the FTS index.
-** Using this method, when tokenizing document text, the tokenizer
-** provides multiple synonyms for each token. So that when a
-** document such as "I won first place" is tokenized, entries are
-** added to the FTS index for "i", "won", "first", "1st" and
-** "place".
-**
-** This way, even if the tokenizer does not provide synonyms
-** when tokenizing query text (it should not - to do so would be
-** inefficient), it doesn't matter if the user queries for
-** 'first + place' or '1st + place', as there are entries in the
-** FTS index corresponding to both forms of the first token.
-**
-**
-** Whether it is parsing document or query text, any call to xToken that
-** specifies a tflags argument with the FTS5_TOKEN_COLOCATED bit
-** is considered to supply a synonym for the previous token. For example,
-** when parsing the document "I won first place", a tokenizer that supports
-** synonyms would call xToken() 5 times, as follows:
-**
-**
-** xToken(pCtx, 0, "i", 1, 0, 1);
-** xToken(pCtx, 0, "won", 3, 2, 5);
-** xToken(pCtx, 0, "first", 5, 6, 11);
-** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
-** xToken(pCtx, 0, "place", 5, 12, 17);
-**
-**
-** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
-** xToken() is called. Multiple synonyms may be specified for a single token
-** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
-** There is no limit to the number of synonyms that may be provided for a
-** single token.
-**
-** In many cases, method (1) above is the best approach. It does not add
-** extra data to the FTS index or require FTS5 to query for multiple terms,
-** so it is efficient in terms of disk space and query speed. However, it
-** does not support prefix queries very well. If, as suggested above, the
-** token "first" is substituted for "1st" by the tokenizer, then the query:
-**
-**
-** ... MATCH '1s*'
-**
-** will not match documents that contain the token "1st" (as the tokenizer
-** will probably not map "1s" to any prefix of "first").
-**
-** For full prefix support, method (3) may be preferred. In this case,
-** because the index contains entries for both "first" and "1st", prefix
-** queries such as 'fi*' or '1s*' will match correctly. However, because
-** extra entries are added to the FTS index, this method uses more space
-** within the database.
-**
-** Method (2) offers a midpoint between (1) and (3). Using this method,
-** a query such as '1s*' will match documents that contain the literal
-** token "1st", but not "first" (assuming the tokenizer is not able to
-** provide synonyms for prefixes). However, a non-prefix query like '1st'
-** will match against "1st" and "first". This method does not require
-** extra disk space, as no extra entries are added to the FTS index.
-** On the other hand, it may require more CPU cycles to run MATCH queries,
-** as separate queries of the FTS index are required for each synonym.
-**
-** When using methods (2) or (3), it is important that the tokenizer only
-** provide synonyms when tokenizing document text (method (2)) or query
-** text (method (3)), not both. Doing so will not cause any errors, but is
-** inefficient.
-*/
-typedef struct Fts5Tokenizer Fts5Tokenizer;
-typedef struct fts5_tokenizer fts5_tokenizer;
-struct fts5_tokenizer {
- int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
- void (*xDelete)(Fts5Tokenizer*);
- int (*xTokenize)(Fts5Tokenizer*,
- void *pCtx,
- int flags, /* Mask of FTS5_TOKENIZE_* flags */
- const char *pText, int nText,
- int (*xToken)(
- void *pCtx, /* Copy of 2nd argument to xTokenize() */
- int tflags, /* Mask of FTS5_TOKEN_* flags */
- const char *pToken, /* Pointer to buffer containing token */
- int nToken, /* Size of token in bytes */
- int iStart, /* Byte offset of token within input text */
- int iEnd /* Byte offset of end of token within input text */
- )
- );
-};
-
-/* Flags that may be passed as the third argument to xTokenize() */
-#define FTS5_TOKENIZE_QUERY 0x0001
-#define FTS5_TOKENIZE_PREFIX 0x0002
-#define FTS5_TOKENIZE_DOCUMENT 0x0004
-#define FTS5_TOKENIZE_AUX 0x0008
-
-/* Flags that may be passed by the tokenizer implementation back to FTS5
-** as the third argument to the supplied xToken callback. */
-#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
-
-/*
-** END OF CUSTOM TOKENIZERS
-*************************************************************************/
-
-/*************************************************************************
-** FTS5 EXTENSION REGISTRATION API
-*/
-typedef struct fts5_api fts5_api;
-struct fts5_api {
- int iVersion; /* Currently always set to 2 */
-
- /* Create a new tokenizer */
- int (*xCreateTokenizer)(
- fts5_api *pApi,
- const char *zName,
- void *pContext,
- fts5_tokenizer *pTokenizer,
- void (*xDestroy)(void*)
- );
-
- /* Find an existing tokenizer */
- int (*xFindTokenizer)(
- fts5_api *pApi,
- const char *zName,
- void **ppContext,
- fts5_tokenizer *pTokenizer
- );
-
- /* Create a new auxiliary function */
- int (*xCreateFunction)(
- fts5_api *pApi,
- const char *zName,
- void *pContext,
- fts5_extension_function xFunction,
- void (*xDestroy)(void*)
- );
-};
-
-/*
-** END OF REGISTRATION API
-*************************************************************************/
-
-#if 0
-} /* end of the 'extern "C"' block */
-#endif
-
-#endif /* _FTS5_H */
-
-/******** End of fts5.h *********/
-
-/************** End of sqlite3.h *********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/*
-** Include the configuration header output by 'configure' if we're using the
-** autoconf-based build
-*/
-#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
-/* #include "config.h" */
-#define SQLITECONFIG_H 1
-#endif
-
-/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
-/************** Begin file sqliteLimit.h *************************************/
-/*
-** 2007 May 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 defines various limits of what SQLite can process.
-*/
-
-/*
-** The maximum length of a TEXT or BLOB in bytes. This also
-** limits the size of a row in a table or index.
-**
-** The hard limit is the ability of a 32-bit signed integer
-** to count the size: 2^31-1 or 2147483647.
-*/
-#ifndef SQLITE_MAX_LENGTH
-# define SQLITE_MAX_LENGTH 1000000000
-#endif
-
-/*
-** This is the maximum number of
-**
-** * Columns in a table
-** * Columns in an index
-** * Columns in a view
-** * Terms in the SET clause of an UPDATE statement
-** * Terms in the result set of a SELECT statement
-** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
-** * Terms in the VALUES clause of an INSERT statement
-**
-** The hard upper limit here is 32676. Most database people will
-** tell you that in a well-normalized database, you usually should
-** not have more than a dozen or so columns in any table. And if
-** that is the case, there is no point in having more than a few
-** dozen values in any of the other situations described above.
-*/
-#ifndef SQLITE_MAX_COLUMN
-# define SQLITE_MAX_COLUMN 2000
-#endif
-
-/*
-** The maximum length of a single SQL statement in bytes.
-**
-** It used to be the case that setting this value to zero would
-** turn the limit off. That is no longer true. It is not possible
-** to turn this limit off.
-*/
-#ifndef SQLITE_MAX_SQL_LENGTH
-# define SQLITE_MAX_SQL_LENGTH 1000000000
-#endif
-
-/*
-** The maximum depth of an expression tree. This is limited to
-** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
-** want to place more severe limits on the complexity of an
-** expression.
-**
-** A value of 0 used to mean that the limit was not enforced.
-** But that is no longer true. The limit is now strictly enforced
-** at all times.
-*/
-#ifndef SQLITE_MAX_EXPR_DEPTH
-# define SQLITE_MAX_EXPR_DEPTH 1000
-#endif
-
-/*
-** The maximum number of terms in a compound SELECT statement.
-** The code generator for compound SELECT statements does one
-** level of recursion for each term. A stack overflow can result
-** if the number of terms is too large. In practice, most SQL
-** never has more than 3 or 4 terms. Use a value of 0 to disable
-** any limit on the number of terms in a compount SELECT.
-*/
-#ifndef SQLITE_MAX_COMPOUND_SELECT
-# define SQLITE_MAX_COMPOUND_SELECT 500
-#endif
-
-/*
-** The maximum number of opcodes in a VDBE program.
-** Not currently enforced.
-*/
-#ifndef SQLITE_MAX_VDBE_OP
-# define SQLITE_MAX_VDBE_OP 250000000
-#endif
-
-/*
-** The maximum number of arguments to an SQL function.
-*/
-#ifndef SQLITE_MAX_FUNCTION_ARG
-# define SQLITE_MAX_FUNCTION_ARG 127
-#endif
-
-/*
-** The suggested maximum number of in-memory pages to use for
-** the main database table and for temporary tables.
-**
-** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
-** which means the cache size is limited to 2048000 bytes of memory.
-** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
-** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
-*/
-#ifndef SQLITE_DEFAULT_CACHE_SIZE
-# define SQLITE_DEFAULT_CACHE_SIZE -2000
-#endif
-
-/*
-** The default number of frames to accumulate in the log file before
-** checkpointing the database in WAL mode.
-*/
-#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
-# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
-#endif
-
-/*
-** The maximum number of attached databases. This must be between 0
-** and 125. The upper bound of 125 is because the attached databases are
-** counted using a signed 8-bit integer which has a maximum value of 127
-** and we have to allow 2 extra counts for the "main" and "temp" databases.
-*/
-#ifndef SQLITE_MAX_ATTACHED
-# define SQLITE_MAX_ATTACHED 10
-#endif
-
-
-/*
-** The maximum value of a ?nnn wildcard that the parser will accept.
-*/
-#ifndef SQLITE_MAX_VARIABLE_NUMBER
-# define SQLITE_MAX_VARIABLE_NUMBER 999
-#endif
-
-/* Maximum page size. The upper bound on this value is 65536. This a limit
-** imposed by the use of 16-bit offsets within each page.
-**
-** Earlier versions of SQLite allowed the user to change this value at
-** compile time. This is no longer permitted, on the grounds that it creates
-** a library that is technically incompatible with an SQLite library
-** compiled with a different limit. If a process operating on a database
-** with a page-size of 65536 bytes crashes, then an instance of SQLite
-** compiled with the default page-size limit will not be able to rollback
-** the aborted transaction. This could lead to database corruption.
-*/
-#ifdef SQLITE_MAX_PAGE_SIZE
-# undef SQLITE_MAX_PAGE_SIZE
-#endif
-#define SQLITE_MAX_PAGE_SIZE 65536
-
-
-/*
-** The default size of a database page.
-*/
-#ifndef SQLITE_DEFAULT_PAGE_SIZE
-# define SQLITE_DEFAULT_PAGE_SIZE 4096
-#endif
-#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
-# undef SQLITE_DEFAULT_PAGE_SIZE
-# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
-#endif
-
-/*
-** Ordinarily, if no value is explicitly provided, SQLite creates databases
-** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
-** device characteristics (sector-size and atomic write() support),
-** SQLite may choose a larger value. This constant is the maximum value
-** SQLite will choose on its own.
-*/
-#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
-# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
-#endif
-#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
-# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
-# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
-#endif
-
-
-/*
-** Maximum number of pages in one database file.
-**
-** This is really just the default value for the max_page_count pragma.
-** This value can be lowered (or raised) at run-time using that the
-** max_page_count macro.
-*/
-#ifndef SQLITE_MAX_PAGE_COUNT
-# define SQLITE_MAX_PAGE_COUNT 1073741823
-#endif
-
-/*
-** Maximum length (in bytes) of the pattern in a LIKE or GLOB
-** operator.
-*/
-#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
-# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
-#endif
-
-/*
-** Maximum depth of recursion for triggers.
-**
-** A value of 1 means that a trigger program will not be able to itself
-** fire any triggers. A value of 0 means that no trigger programs at all
-** may be executed.
-*/
-#ifndef SQLITE_MAX_TRIGGER_DEPTH
-# define SQLITE_MAX_TRIGGER_DEPTH 1000
-#endif
-
-/************** End of sqliteLimit.h *****************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/* Disable nuisance warnings on Borland compilers */
-#if defined(__BORLANDC__)
-#pragma warn -rch /* unreachable code */
-#pragma warn -ccc /* Condition is always true or false */
-#pragma warn -aus /* Assigned value is never used */
-#pragma warn -csu /* Comparing signed and unsigned */
-#pragma warn -spa /* Suspicious pointer arithmetic */
-#endif
-
-/*
-** Include standard header files as necessary
-*/
-#ifdef HAVE_STDINT_H
-#include
-#endif
-#ifdef HAVE_INTTYPES_H
-#include
-#endif
-
-/*
-** 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 defined(__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
-
-/*
-** A macro to hint to the compiler that a function should not be
-** inlined.
-*/
-#if defined(__GNUC__)
-# define SQLITE_NOINLINE __attribute__((noinline))
-#elif defined(_MSC_VER) && _MSC_VER>=1310
-# define SQLITE_NOINLINE __declspec(noinline)
-#else
-# define SQLITE_NOINLINE
-#endif
-
-/*
-** Make sure that the compiler intrinsics we desire are enabled when
-** compiling with an appropriate version of MSVC unless prevented by
-** the SQLITE_DISABLE_INTRINSIC define.
-*/
-#if !defined(SQLITE_DISABLE_INTRINSIC)
-# if defined(_MSC_VER) && _MSC_VER>=1400
-# if !defined(_WIN32_WCE)
-# include
-# pragma intrinsic(_byteswap_ushort)
-# pragma intrinsic(_byteswap_ulong)
-# pragma intrinsic(_byteswap_uint64)
-# pragma intrinsic(_ReadWriteBarrier)
-# else
-# include
-# endif
-# endif
-#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 library 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.
-**
-** To ensure that the correct value of "THREADSAFE" is reported when querying
-** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
-** logic is partially replicated in ctime.c. If it is updated here, it should
-** also be updated there.
-*/
-#if !defined(SQLITE_THREADSAFE)
-# if defined(THREADSAFE)
-# define SQLITE_THREADSAFE THREADSAFE
-# else
-# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
-# endif
-#endif
-
-/*
-** Powersafe overwrite is on by default. But can be turned off using
-** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
-*/
-#ifndef SQLITE_POWERSAFE_OVERWRITE
-# define SQLITE_POWERSAFE_OVERWRITE 1
-#endif
-
-/*
-** EVIDENCE-OF: R-25715-37072 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.
-*/
-#if !defined(SQLITE_DEFAULT_MEMSTATUS)
-# define 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_WIN32_MALLOC // Use Win32 native heap API
-** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
-** SQLITE_MEMDEBUG // Debugging version of system malloc()
-**
-** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
-** assert() macro is enabled, each call into the Win32 native heap subsystem
-** will cause HeapValidate to be called. If heap validation should fail, an
-** assertion will be triggered.
-**
-** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
-** the default.
-*/
-#if defined(SQLITE_SYSTEM_MALLOC) \
- + defined(SQLITE_WIN32_MALLOC) \
- + defined(SQLITE_ZERO_MALLOC) \
- + defined(SQLITE_MEMDEBUG)>1
-# error "Two or more of the following compile-time configuration options\
- are defined but at most one is allowed:\
- SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
- SQLITE_ZERO_MALLOC"
-#endif
-#if defined(SQLITE_SYSTEM_MALLOC) \
- + defined(SQLITE_WIN32_MALLOC) \
- + defined(SQLITE_ZERO_MALLOC) \
- + defined(SQLITE_MEMDEBUG)==0
-# define SQLITE_SYSTEM_MALLOC 1
-#endif
-
-/*
-** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
-** sizes of memory allocations below this value where possible.
-*/
-#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
-# define SQLITE_MALLOC_SOFT_LIMIT 1024
-#endif
-
-/*
-** We need to define _XOPEN_SOURCE as follows in order to enable
-** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
-** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
-** it.
-*/
-#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
-# define _XOPEN_SOURCE 600
-#endif
-
-/*
-** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
-** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
-** make it true by defining or undefining NDEBUG.
-**
-** Setting NDEBUG makes the code smaller and faster by disabling the
-** assert() statements in the code. So we want the default action
-** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
-** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
-** feature.
-*/
-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
-# define NDEBUG 1
-#endif
-#if defined(NDEBUG) && defined(SQLITE_DEBUG)
-# undef NDEBUG
-#endif
-
-/*
-** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
-*/
-#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
-# define SQLITE_ENABLE_EXPLAIN_COMMENTS 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.
-**
-*/
-#ifdef SQLITE_COVERAGE_TEST
-SQLITE_PRIVATE void sqlite3Coverage(int);
-# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
-#else
-# define testcase(X)
-#endif
-
-/*
-** The TESTONLY macro is used to enclose variable declarations or
-** other bits of code that are needed to support the arguments
-** within testcase() and assert() macros.
-*/
-#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
-# define TESTONLY(X) X
-#else
-# define TESTONLY(X)
-#endif
-
-/*
-** Sometimes we need a small amount of code such as a variable initialization
-** to setup for a later assert() statement. We do not want this code to
-** appear when assert() is disabled. The following macro is therefore
-** used to contain that setup code. The "VVA" acronym stands for
-** "Verification, Validation, and Accreditation". In other words, the
-** code within VVA_ONLY() will only run during verification processes.
-*/
-#ifndef 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 they specify will
-** not be counted as untested code.
-*/
-#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
-# define ALWAYS(X) (1)
-# define NEVER(X) (0)
-#elif !defined(NDEBUG)
-# define ALWAYS(X) ((X)?1:(assert(0),0))
-# define NEVER(X) ((X)?(assert(0),1):0)
-#else
-# define ALWAYS(X) (X)
-# define NEVER(X) (X)
-#endif
-
-/*
-** Some conditionals are optimizations only. In other words, if the
-** conditionals are replaced with a constant 1 (true) or 0 (false) then
-** the correct answer is still obtained, though perhaps not as quickly.
-**
-** The following macros mark these optimizations conditionals.
-*/
-#if defined(SQLITE_MUTATION_TEST)
-# define OK_IF_ALWAYS_TRUE(X) (1)
-# define OK_IF_ALWAYS_FALSE(X) (0)
-#else
-# define OK_IF_ALWAYS_TRUE(X) (X)
-# define OK_IF_ALWAYS_FALSE(X) (X)
-#endif
-
-/*
-** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
-** defined. We need to defend against those failures when testing with
-** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
-** during a normal build. The following macro can be used to disable tests
-** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
-*/
-#if defined(SQLITE_TEST_REALLOC_STRESS)
-# define ONLY_IF_REALLOC_STRESS(X) (X)
-#elif !defined(NDEBUG)
-# define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
-#else
-# define ONLY_IF_REALLOC_STRESS(X) (0)
-#endif
-
-/*
-** Declarations used for tracing the operating system interfaces.
-*/
-#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
- (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
- extern int sqlite3OSTrace;
-# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
-# define SQLITE_HAVE_OS_TRACE
-#else
-# define OSTRACE(X)
-# undef SQLITE_HAVE_OS_TRACE
-#endif
-
-/*
-** Is the sqlite3ErrName() function needed in the build? Currently,
-** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
-** OSTRACE is enabled), and by several "test*.c" files (which are
-** compiled using SQLITE_TEST).
-*/
-#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
- (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
-# define SQLITE_NEED_ERR_NAME
-#else
-# undef SQLITE_NEED_ERR_NAME
-#endif
-
-/*
-** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
-*/
-#ifdef SQLITE_OMIT_EXPLAIN
-# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
-#endif
-
-/*
-** Return true (non-zero) if the input is an 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.
-*/
-#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. These hints could,
-** in theory, be used by the compiler to generate better code, but
-** currently they are just comments for human readers.
-*/
-#define likely(X) (X)
-#define unlikely(X) (X)
-
-/************** Include hash.h in the middle of sqliteInt.h ******************/
-/************** Begin file hash.h ********************************************/
-/*
-** 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 implementation
-** used in SQLite.
-*/
-#ifndef 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.
-*/
-struct Hash {
- unsigned int htsize; /* Number of buckets in the hash table */
- unsigned int count; /* Number of entries in this table */
- HashElem *first; /* The first element of the array */
- struct _ht { /* the hash table */
- unsigned int count; /* Number of entries with this hash */
- HashElem *chain; /* Pointer to first entry with this hash */
- } *ht;
-};
-
-/* 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.
-*/
-struct HashElem {
- HashElem *next, *prev; /* Next and previous elements in the table */
- void *data; /* Data associated with this element */
- const char *pKey; /* Key associated with this element */
-};
-
-/*
-** Access routines. To delete, insert a NULL pointer.
-*/
-SQLITE_PRIVATE void sqlite3HashInit(Hash*);
-SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
-SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
-SQLITE_PRIVATE 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)
-#define sqliteHashNext(E) ((E)->next)
-#define sqliteHashData(E) ((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 */
-
-/************** End of hash.h ************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include parse.h in the middle of sqliteInt.h *****************/
-/************** Begin file parse.h *******************************************/
-#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_WITHOUT 25
-#define TK_COMMA 26
-#define TK_ABORT 27
-#define TK_ACTION 28
-#define TK_AFTER 29
-#define TK_ANALYZE 30
-#define TK_ASC 31
-#define TK_ATTACH 32
-#define TK_BEFORE 33
-#define TK_BY 34
-#define TK_CASCADE 35
-#define TK_CAST 36
-#define TK_CONFLICT 37
-#define TK_DATABASE 38
-#define TK_DESC 39
-#define TK_DETACH 40
-#define TK_EACH 41
-#define TK_FAIL 42
-#define TK_OR 43
-#define TK_AND 44
-#define TK_IS 45
-#define TK_MATCH 46
-#define TK_LIKE_KW 47
-#define TK_BETWEEN 48
-#define TK_IN 49
-#define TK_ISNULL 50
-#define TK_NOTNULL 51
-#define TK_NE 52
-#define TK_EQ 53
-#define TK_GT 54
-#define TK_LE 55
-#define TK_LT 56
-#define TK_GE 57
-#define TK_ESCAPE 58
-#define TK_ID 59
-#define TK_COLUMNKW 60
-#define TK_DO 61
-#define TK_FOR 62
-#define TK_IGNORE 63
-#define TK_INITIALLY 64
-#define TK_INSTEAD 65
-#define TK_NO 66
-#define TK_KEY 67
-#define TK_OF 68
-#define TK_OFFSET 69
-#define TK_PRAGMA 70
-#define TK_RAISE 71
-#define TK_RECURSIVE 72
-#define TK_REPLACE 73
-#define TK_RESTRICT 74
-#define TK_ROW 75
-#define TK_ROWS 76
-#define TK_TRIGGER 77
-#define TK_VACUUM 78
-#define TK_VIEW 79
-#define TK_VIRTUAL 80
-#define TK_WITH 81
-#define TK_CURRENT 82
-#define TK_FOLLOWING 83
-#define TK_PARTITION 84
-#define TK_PRECEDING 85
-#define TK_RANGE 86
-#define TK_UNBOUNDED 87
-#define TK_EXCLUDE 88
-#define TK_GROUPS 89
-#define TK_OTHERS 90
-#define TK_TIES 91
-#define TK_REINDEX 92
-#define TK_RENAME 93
-#define TK_CTIME_KW 94
-#define TK_ANY 95
-#define TK_BITAND 96
-#define TK_BITOR 97
-#define TK_LSHIFT 98
-#define TK_RSHIFT 99
-#define TK_PLUS 100
-#define TK_MINUS 101
-#define TK_STAR 102
-#define TK_SLASH 103
-#define TK_REM 104
-#define TK_CONCAT 105
-#define TK_COLLATE 106
-#define TK_BITNOT 107
-#define TK_ON 108
-#define TK_INDEXED 109
-#define TK_STRING 110
-#define TK_JOIN_KW 111
-#define TK_CONSTRAINT 112
-#define TK_DEFAULT 113
-#define TK_NULL 114
-#define TK_PRIMARY 115
-#define TK_UNIQUE 116
-#define TK_CHECK 117
-#define TK_REFERENCES 118
-#define TK_AUTOINCR 119
-#define TK_INSERT 120
-#define TK_DELETE 121
-#define TK_UPDATE 122
-#define TK_SET 123
-#define TK_DEFERRABLE 124
-#define TK_FOREIGN 125
-#define TK_DROP 126
-#define TK_UNION 127
-#define TK_ALL 128
-#define TK_EXCEPT 129
-#define TK_INTERSECT 130
-#define TK_SELECT 131
-#define TK_VALUES 132
-#define TK_DISTINCT 133
-#define TK_DOT 134
-#define TK_FROM 135
-#define TK_JOIN 136
-#define TK_USING 137
-#define TK_ORDER 138
-#define TK_GROUP 139
-#define TK_HAVING 140
-#define TK_LIMIT 141
-#define TK_WHERE 142
-#define TK_INTO 143
-#define TK_NOTHING 144
-#define TK_FLOAT 145
-#define TK_BLOB 146
-#define TK_INTEGER 147
-#define TK_VARIABLE 148
-#define TK_CASE 149
-#define TK_WHEN 150
-#define TK_THEN 151
-#define TK_ELSE 152
-#define TK_INDEX 153
-#define TK_ALTER 154
-#define TK_ADD 155
-#define TK_WINDOW 156
-#define TK_OVER 157
-#define TK_FILTER 158
-#define TK_TRUEFALSE 159
-#define TK_ISNOT 160
-#define TK_FUNCTION 161
-#define TK_COLUMN 162
-#define TK_AGG_FUNCTION 163
-#define TK_AGG_COLUMN 164
-#define TK_UMINUS 165
-#define TK_UPLUS 166
-#define TK_TRUTH 167
-#define TK_REGISTER 168
-#define TK_VECTOR 169
-#define TK_SELECT_COLUMN 170
-#define TK_IF_NULL_ROW 171
-#define TK_ASTERISK 172
-#define TK_SPAN 173
-#define TK_SPACE 174
-#define TK_ILLEGAL 175
-
-/************** End of parse.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-#include
-#include
-#include
-#include
-#include
-
-/*
-** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
-** This allows better measurements of where memcpy() is used when running
-** cachegrind. But this macro version of memcpy() is very slow so it
-** should not be used in production. This is a performance measurement
-** hack only.
-*/
-#ifdef SQLITE_INLINE_MEMCPY
-# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
- int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
-#endif
-
-/*
-** If compiling for a processor that lacks floating point support,
-** substitute integer for floating-point
-*/
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define double sqlite_int64
-# define float sqlite_int64
-# define LONGDOUBLE_TYPE sqlite_int64
-# ifndef 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
-#ifndef SQLITE_BIG_DBL
-# 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 #ifndef statements.
-*/
-#ifdef SQLITE_OMIT_TEMPDB
-#define OMIT_TEMPDB 1
-#else
-#define 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.
-*/
-#define SQLITE_MAX_FILE_FORMAT 4
-#ifndef SQLITE_DEFAULT_FILE_FORMAT
-# define SQLITE_DEFAULT_FILE_FORMAT 4
-#endif
-
-/*
-** Determine whether triggers are recursive by default. This can be
-** changed at run-time using a pragma.
-*/
-#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
-# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
-#endif
-
-/*
-** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
-** on the command-line
-*/
-#ifndef SQLITE_TEMP_STORE
-# define SQLITE_TEMP_STORE 1
-#endif
-
-/*
-** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
-** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
-** to zero.
-*/
-#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
-# undef SQLITE_MAX_WORKER_THREADS
-# define SQLITE_MAX_WORKER_THREADS 0
-#endif
-#ifndef SQLITE_MAX_WORKER_THREADS
-# define SQLITE_MAX_WORKER_THREADS 8
-#endif
-#ifndef SQLITE_DEFAULT_WORKER_THREADS
-# define SQLITE_DEFAULT_WORKER_THREADS 0
-#endif
-#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
-# undef SQLITE_MAX_WORKER_THREADS
-# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
-#endif
-
-/*
-** The default initial allocation for the pagecache when using separate
-** pagecaches for each database connection. A positive number is the
-** number of pages. A negative number N translations means that a buffer
-** of -1024*N bytes is allocated and used for as many pages as it will hold.
-**
-** The default value of "20" was choosen to minimize the run-time of the
-** speedtest1 test program with options: --shrink-memory --reprepare
-*/
-#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
-# define SQLITE_DEFAULT_PCACHE_INITSZ 20
-#endif
-
-/*
-** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
-*/
-#ifndef SQLITE_DEFAULT_SORTERREF_SIZE
-# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
-#endif
-
-/*
-** The compile-time options SQLITE_MMAP_READWRITE and
-** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
-** You must choose one or the other (or neither) but not both.
-*/
-#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
-#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
-#endif
-
-/*
-** GCC does not define the offsetof() macro so we'll have to do it
-** ourselves.
-*/
-#ifndef offsetof
-#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
-#endif
-
-/*
-** Macros to compute minimum and maximum of two numbers.
-*/
-#ifndef MIN
-# define MIN(A,B) ((A)<(B)?(A):(B))
-#endif
-#ifndef MAX
-# define MAX(A,B) ((A)>(B)?(A):(B))
-#endif
-
-/*
-** Swap two objects of type TYPE.
-*/
-#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
-
-/*
-** Check to see if this machine uses EBCDIC. (Yes, believe it or
-** not, there are still machines out there that use EBCDIC.)
-*/
-#if 'A' == '\301'
-# define SQLITE_EBCDIC 1
-#else
-# 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 '-DUINTPTR_TYPE=long long int' ...
-*/
-#ifndef UINT32_TYPE
-# ifdef HAVE_UINT32_T
-# define UINT32_TYPE uint32_t
-# else
-# define UINT32_TYPE unsigned int
-# endif
-#endif
-#ifndef UINT16_TYPE
-# ifdef HAVE_UINT16_T
-# define UINT16_TYPE uint16_t
-# else
-# define UINT16_TYPE unsigned short int
-# endif
-#endif
-#ifndef INT16_TYPE
-# ifdef HAVE_INT16_T
-# define INT16_TYPE int16_t
-# else
-# define INT16_TYPE short int
-# endif
-#endif
-#ifndef UINT8_TYPE
-# ifdef HAVE_UINT8_T
-# define UINT8_TYPE uint8_t
-# else
-# define UINT8_TYPE unsigned char
-# endif
-#endif
-#ifndef INT8_TYPE
-# ifdef HAVE_INT8_T
-# define INT8_TYPE int8_t
-# else
-# define INT8_TYPE signed char
-# endif
-#endif
-#ifndef LONGDOUBLE_TYPE
-# define LONGDOUBLE_TYPE long double
-#endif
-typedef sqlite_int64 i64; /* 8-byte signed integer */
-typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
-typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
-typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
-typedef INT16_TYPE i16; /* 2-byte signed integer */
-typedef UINT8_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)
-
-/*
-** The datatype used to store estimates of the number of rows in a
-** table or index. This is an unsigned integer type. For 99.9% of
-** the world, a 32-bit integer is sufficient. But a 64-bit integer
-** can be used at compile-time if desired.
-*/
-#ifdef SQLITE_64BIT_STATS
- typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
-#else
- typedef u32 tRowcnt; /* 32-bit is the default */
-#endif
-
-/*
-** Estimated quantities used for query planning are stored as 16-bit
-** logarithms. For quantity X, the value stored is 10*log2(X). This
-** gives a possible range of values of approximately 1.0e986 to 1e-986.
-** But the allowed values are "grainy". Not every value is representable.
-** For example, quantities 16 and 17 are both represented by a LogEst
-** of 40. However, since LogEst quantities are suppose to be estimates,
-** not exact values, this imprecision is not a problem.
-**
-** "LogEst" is short for "Logarithmic Estimate".
-**
-** Examples:
-** 1 -> 0 20 -> 43 10000 -> 132
-** 2 -> 10 25 -> 46 25000 -> 146
-** 3 -> 16 100 -> 66 1000000 -> 199
-** 4 -> 20 1000 -> 99 1048576 -> 200
-** 10 -> 33 1024 -> 100 4294967296 -> 320
-**
-** The LogEst can be negative to indicate fractional values.
-** Examples:
-**
-** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
-*/
-typedef INT16_TYPE LogEst;
-
-/*
-** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
-*/
-#ifndef SQLITE_PTRSIZE
-# if defined(__SIZEOF_POINTER__)
-# define SQLITE_PTRSIZE __SIZEOF_POINTER__
-# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
- defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
- (defined(__TOS_AIX__) && !defined(__64BIT__))
-# define SQLITE_PTRSIZE 4
-# else
-# define SQLITE_PTRSIZE 8
-# endif
-#endif
-
-/* The uptr type is an unsigned integer large enough to hold a pointer
-*/
-#if defined(HAVE_STDINT_H)
- typedef uintptr_t uptr;
-#elif SQLITE_PTRSIZE==4
- typedef u32 uptr;
-#else
- typedef u64 uptr;
-#endif
-
-/*
-** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
-** something between S (inclusive) and E (exclusive).
-**
-** In other words, S is a buffer and E is a pointer to the first byte after
-** the end of buffer S. This macro returns true if P points to something
-** contained within the buffer S.
-*/
-#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
-
-
-/*
-** Macros to determine whether the machine is big or little endian,
-** and whether or not that determination is run-time or compile-time.
-**
-** For best performance, an attempt is made to guess at the byte-order
-** using C-preprocessor macros. If that is unsuccessful, or if
-** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
-** at run-time.
-*/
-#ifndef SQLITE_BYTEORDER
-# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
- defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
- defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
- defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
-# define SQLITE_BYTEORDER 1234
-# elif defined(sparc) || defined(__ppc__) || \
- defined(__ARMEB__) || defined(__AARCH64EB__)
-# define SQLITE_BYTEORDER 4321
-# else
-# define SQLITE_BYTEORDER 0
-# endif
-#endif
-#if SQLITE_BYTEORDER==4321
-# define SQLITE_BIGENDIAN 1
-# define SQLITE_LITTLEENDIAN 0
-# define SQLITE_UTF16NATIVE SQLITE_UTF16BE
-#elif SQLITE_BYTEORDER==1234
-# define SQLITE_BIGENDIAN 0
-# define SQLITE_LITTLEENDIAN 1
-# define SQLITE_UTF16NATIVE SQLITE_UTF16LE
-#else
-# ifdef SQLITE_AMALGAMATION
- const int sqlite3one = 1;
-# else
- extern const int sqlite3one;
-# endif
-# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
-# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
-# 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)
-
-/*
-** 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)
-
-/*
-** Round down to the nearest multiple of 8
-*/
-#define ROUNDDOWN8(x) ((x)&~7)
-
-/*
-** Assert that the pointer X is aligned to an 8-byte boundary. This
-** macro is used only within assert() to verify that the code gets
-** all alignment restrictions correct.
-**
-** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
-** underlying malloc() implementation might return us 4-byte aligned
-** pointers. In that case, only verify 4-byte alignment.
-*/
-#ifdef 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
-
-/*
-** Disable MMAP on platforms where it is known to not work
-*/
-#if defined(__OpenBSD__) || defined(__QNXNTO__)
-# undef SQLITE_MAX_MMAP_SIZE
-# define SQLITE_MAX_MMAP_SIZE 0
-#endif
-
-/*
-** Default maximum size of memory used by memory-mapped I/O in the VFS
-*/
-#ifdef __APPLE__
-# include
-#endif
-#ifndef SQLITE_MAX_MMAP_SIZE
-# if defined(__linux__) \
- || defined(_WIN32) \
- || (defined(__APPLE__) && defined(__MACH__)) \
- || defined(__sun) \
- || defined(__FreeBSD__) \
- || defined(__DragonFly__)
-# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
-# else
-# define SQLITE_MAX_MMAP_SIZE 0
-# endif
-#endif
-
-/*
-** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
-** default MMAP_SIZE is specified at compile-time, make sure that it does
-** not exceed the maximum mmap size.
-*/
-#ifndef SQLITE_DEFAULT_MMAP_SIZE
-# define SQLITE_DEFAULT_MMAP_SIZE 0
-#endif
-#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
-# undef SQLITE_DEFAULT_MMAP_SIZE
-# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
-#endif
-
-/*
-** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
-** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
-** define SQLITE_ENABLE_STAT3_OR_STAT4
-*/
-#ifdef SQLITE_ENABLE_STAT4
-# undef SQLITE_ENABLE_STAT3
-# define SQLITE_ENABLE_STAT3_OR_STAT4 1
-#elif SQLITE_ENABLE_STAT3
-# define SQLITE_ENABLE_STAT3_OR_STAT4 1
-#elif SQLITE_ENABLE_STAT3_OR_STAT4
-# undef SQLITE_ENABLE_STAT3_OR_STAT4
-#endif
-
-/*
-** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
-** the Select query generator tracing logic is turned on.
-*/
-#if defined(SQLITE_ENABLE_SELECTTRACE)
-# define SELECTTRACE_ENABLED 1
-#else
-# define SELECTTRACE_ENABLED 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;
-struct BusyHandler {
- int (*xBusyHandler)(void *,int); /* The busy callback */
- void *pBusyArg; /* First arg to busy callback */
- int nBusy; /* Incremented with each busy call */
- u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
-};
-
-/*
-** 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.
-*/
-#define MASTER_NAME "sqlite_master"
-#define TEMP_MASTER_NAME "sqlite_temp_master"
-
-/*
-** The root-page of the master database table.
-*/
-#define MASTER_ROOT 1
-
-/*
-** The name of the schema table.
-*/
-#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(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])))
-
-/*
-** Determine if the argument is a power of two
-*/
-#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
-
-/*
-** The following value as a destructor means to use sqlite3DbFree().
-** The sqlite3DbFree() routine requires two parameters instead of the
-** one parameter that destructors normally want. So we have to introduce
-** this magic value that the code knows to handle differently. Any
-** pointer will work here as long as it is distinct from SQLITE_STATIC
-** and SQLITE_TRANSIENT.
-*/
-#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
-
-/*
-** 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.
-*/
-#ifdef 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)
-SQLITE_API int sqlite3_wsd_init(int N, int J);
-SQLITE_API void *sqlite3_wsd_find(void *K, int L);
-#else
- #define SQLITE_WSD
- #define GLOBAL(t,v) v
- #define sqlite3GlobalConfig sqlite3Config
-#endif
-
-/*
-** The following macros are used to suppress compiler warnings and to
-** make it clear to human readers when a function parameter is deliberately
-** left unused within the body of a function. This usually happens when
-** a function is called via a function pointer. For example the
-** implementation of an SQL aggregate step callback may not use the
-** parameter indicating the number of arguments passed to the aggregate,
-** if it knows that this is enforced elsewhere.
-**
-** When a function parameter is not used at all within the body of a function,
-** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
-** However, these macros may also be used to suppress warnings related to
-** parameters that may or may not be used depending on compilation options.
-** For example those parameters only used in assert() statements. In these
-** cases the parameters are named as per the usual conventions.
-*/
-#define UNUSED_PARAMETER(x) (void)(x)
-#define UNUSED_PARAMETER2(x,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 FKey FKey;
-typedef struct FuncDestructor FuncDestructor;
-typedef struct FuncDef FuncDef;
-typedef struct FuncDefHash FuncDefHash;
-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 PreUpdate PreUpdate;
-typedef struct PrintfArguments PrintfArguments;
-typedef struct RenameToken RenameToken;
-typedef struct RowSet RowSet;
-typedef struct Savepoint Savepoint;
-typedef struct Select Select;
-typedef struct SQLiteThread SQLiteThread;
-typedef struct SelectDest SelectDest;
-typedef struct SrcList SrcList;
-typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
-typedef struct Table Table;
-typedef struct TableLock TableLock;
-typedef struct Token Token;
-typedef struct TreeView TreeView;
-typedef struct Trigger Trigger;
-typedef struct TriggerPrg TriggerPrg;
-typedef struct TriggerStep TriggerStep;
-typedef struct UnpackedRecord UnpackedRecord;
-typedef struct Upsert Upsert;
-typedef struct VTable VTable;
-typedef struct VtabCtx VtabCtx;
-typedef struct Walker Walker;
-typedef struct WhereInfo WhereInfo;
-typedef struct Window Window;
-typedef struct With With;
-
-
-/*
-** The bitmask datatype defined below is used for various optimizations.
-**
-** Changing this from a 64-bit to a 32-bit type limits the number of
-** tables in a join to 32 instead of 64. But it also reduces the size
-** of the library by 738 bytes on ix86.
-*/
-#ifdef SQLITE_BITMASK_TYPE
- typedef SQLITE_BITMASK_TYPE Bitmask;
-#else
- typedef u64 Bitmask;
-#endif
-
-/*
-** The number of bits in a Bitmask. "BMS" means "BitMask Size".
-*/
-#define BMS ((int)(sizeof(Bitmask)*8))
-
-/*
-** A bit in a Bitmask
-*/
-#define MASKBIT(n) (((Bitmask)1)<<(n))
-#define MASKBIT32(n) (((unsigned int)1)<<(n))
-#define ALLBITS ((Bitmask)-1)
-
-/* A VList object records a mapping between parameters/variables/wildcards
-** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
-** variable number associated with that parameter. See the format description
-** on the sqlite3VListAdd() routine for more information. A VList is really
-** just an array of integers.
-*/
-typedef int VList;
-
-/*
-** 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 in the middle of sqliteInt.h *****************/
-/************** Begin file btree.h *******************************************/
-/*
-** 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.
-*/
-#ifndef SQLITE_BTREE_H
-#define SQLITE_BTREE_H
-
-/* TODO: This definition is just included so other modules compile. It
-** needs to be revisited.
-*/
-#define SQLITE_N_BTREE_META 16
-
-/*
-** 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".
-*/
-#ifndef SQLITE_DEFAULT_AUTOVACUUM
- #define SQLITE_DEFAULT_AUTOVACUUM 0
-#endif
-
-#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
-#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
-#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
-
-/*
-** Forward declarations of structure
-*/
-typedef struct Btree Btree;
-typedef struct BtCursor BtCursor;
-typedef struct BtShared BtShared;
-typedef struct BtreePayload BtreePayload;
-
-
-SQLITE_PRIVATE int sqlite3BtreeOpen(
- sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
- const char *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_MEMORY 2 /* This is an in-memory DB */
-#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
-#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
-
-SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
-#if SQLITE_MAX_MMAP_SIZE>0
-SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
-#endif
-SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
-SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
-SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
-SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
-SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
-SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
-SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
-SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
-SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
-SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
-SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
-SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
-#ifndef SQLITE_OMIT_SHARED_CACHE
-SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
-#endif
-SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
-
-SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
-SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
-SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
-
-SQLITE_PRIVATE 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 */
-
-SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
-SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
-SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
-
-SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
-SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
-
-SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
-
-/*
-** 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).
-**
-** The BTREE_DATA_VERSION value is not really a value stored in the header.
-** It is a read-only number computed by the pager. But we merge it with
-** the header value access routines since its access pattern is the same.
-** Call it a "virtual meta value".
-*/
-#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
-#define BTREE_APPLICATION_ID 8
-#define BTREE_DATA_VERSION 15 /* A virtual meta-value */
-
-/*
-** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
-** interface.
-**
-** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
-**
-** The first argument is an Expr* (which is guaranteed to be constant for
-** the lifetime of the cursor) that defines constraints on which rows
-** might be fetched with this cursor. The Expr* tree may contain
-** TK_REGISTER nodes that refer to values stored in the array of registers
-** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
-** then the value of the node is the value in Mem[pExpr.iTable]. Any
-** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
-** column of the b-tree of the cursor. The Expr tree will not contain
-** any function calls nor subqueries nor references to b-trees other than
-** the cursor being hinted.
-**
-** The design of the _RANGE hint is aid b-tree implementations that try
-** to prefetch content from remote machines - to provide those
-** implementations with limits on what needs to be prefetched and thereby
-** reduce network bandwidth.
-**
-** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
-** standard SQLite. The other hints are provided for extentions that use
-** the SQLite parser and code generator but substitute their own storage
-** engine.
-*/
-#define BTREE_HINT_RANGE 0 /* Range constraints on queries */
-
-/*
-** Values that may be OR'd together to form the argument to the
-** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
-**
-** The BTREE_BULKLOAD flag is set on index cursors when the index is going
-** to be filled with content that is already in sorted order.
-**
-** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
-** OP_SeekLE opcodes for a range search, but where the range of entries
-** selected will all have the same key. In other words, the cursor will
-** be used only for equality key searches.
-**
-*/
-#define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
-#define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
-
-/*
-** Flags passed as the third argument to sqlite3BtreeCursor().
-**
-** For read-only cursors the wrFlag argument is always zero. For read-write
-** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
-** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
-** only be used by SQLite for the following:
-**
-** * to seek to and then delete specific entries, and/or
-**
-** * to read values that will be used to create keys that other
-** BTREE_FORDELETE cursors will seek to and delete.
-**
-** The BTREE_FORDELETE flag is an optimization hint. It is not used by
-** by this, the native b-tree engine of SQLite, but it is available to
-** alternative storage engines that might be substituted in place of this
-** b-tree system. For alternative storage engines in which a delete of
-** the main table row automatically deletes corresponding index rows,
-** the FORDELETE flag hint allows those alternative storage engines to
-** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
-** and DELETE operations as no-ops, and any READ operation against a
-** FORDELETE cursor may return a null row: 0x01 0x00.
-*/
-#define BTREE_WRCSR 0x00000004 /* read-write cursor */
-#define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
-
-SQLITE_PRIVATE 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 */
-);
-SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
-SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
-SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
-SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
-#ifdef SQLITE_ENABLE_CURSOR_HINTS
-SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
-#endif
-
-SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
- BtCursor*,
- UnpackedRecord *pUnKey,
- i64 intKey,
- int bias,
- int *pRes
-);
-SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
-SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
-
-/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
-#define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
-#define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
-#define BTREE_APPEND 0x08 /* Insert is likely an append */
-
-/* An instance of the BtreePayload object describes the content of a single
-** entry in either an index or table btree.
-**
-** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
-** an arbitrary key and no data. These btrees have pKey,nKey set to the
-** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
-** fields give an array of Mem objects that are a decomposition of the key.
-** The nMem field might be zero, indicating that no decomposition is available.
-**
-** Table btrees (used for rowid tables) contain an integer rowid used as
-** the key and passed in the nKey field. The pKey field is zero.
-** pData,nData hold the content of the new entry. nZero extra zero bytes
-** are appended to the end of the content when constructing the entry.
-** The aMem,nMem fields are uninitialized for table btrees.
-**
-** Field usage summary:
-**
-** Table BTrees Index Btrees
-**
-** pKey always NULL encoded key
-** nKey the ROWID length of pKey
-** pData data not used
-** aMem not used decomposed key value
-** nMem not used entries in aMem
-** nData length of pData not used
-** nZero extra zeros after pData not used
-**
-** This object is used to pass information into sqlite3BtreeInsert(). The
-** same information used to be passed as five separate parameters. But placing
-** the information into this object helps to keep the interface more
-** organized and understandable, and it also helps the resulting code to
-** run a little faster by using fewer registers for parameter passing.
-*/
-struct BtreePayload {
- const void *pKey; /* Key content for indexes. NULL for tables */
- sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
- const void *pData; /* Data for tables. */
- sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
- u16 nMem; /* Number of aMem[] value. Might be zero */
- int nData; /* Size of pData. 0 if none. */
- int nZero; /* Extra zero data appended after pData,nData */
-};
-
-SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
- int flags, int seekResult);
-SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
-SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
-SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
-SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
-#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
-SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
-#endif
-SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
-SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
-SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
-
-SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
-SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
-SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
-
-#ifndef SQLITE_OMIT_INCRBLOB
-SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
-SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
-#endif
-SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
-SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
-SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
-SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
-SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
-
-#ifndef NDEBUG
-SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
-#endif
-SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
-
-#ifndef SQLITE_OMIT_BTREECOUNT
-SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
-#endif
-
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
-SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
-#endif
-
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE 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.
-*/
-#ifndef SQLITE_OMIT_SHARED_CACHE
-SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
-SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
-SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
-SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
-SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
-#else
-# define sqlite3BtreeEnter(X)
-# define sqlite3BtreeEnterAll(X)
-# define sqlite3BtreeSharable(X) 0
-# define sqlite3BtreeEnterCursor(X)
-# define sqlite3BtreeConnectionCount(X) 1
-#endif
-
-#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
-SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
-SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
-SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
-#ifndef NDEBUG
- /* These routines are used inside assert() statements only. */
-SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
-SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
-#endif
-#else
-
-# define sqlite3BtreeLeave(X)
-# define sqlite3BtreeLeaveCursor(X)
-# define sqlite3BtreeLeaveAll(X)
-
-# define sqlite3BtreeHoldsMutex(X) 1
-# define sqlite3BtreeHoldsAllMutexes(X) 1
-# define sqlite3SchemaMutexHeld(X,Y,Z) 1
-#endif
-
-
-#endif /* SQLITE_BTREE_H */
-
-/************** End of btree.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include vdbe.h in the middle of sqliteInt.h ******************/
-/************** Begin file vdbe.h ********************************************/
-/*
-** 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.
-*/
-#ifndef 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 sqlite3_value 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:
-*/
-struct VdbeOp {
- u8 opcode; /* What operation to perform */
- signed char p4type; /* One of the P4_xxx constants for p4 */
- u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
- int p1; /* First operand */
- int p2; /* Second parameter (often the jump destination) */
- int p3; /* The third parameter */
- union p4union { /* fourth parameter */
- int i; /* Integer value if p4type==P4_INT32 */
- void *p; /* Generic pointer */
- char *z; /* Pointer to data for string (char array) types */
- i64 *pI64; /* Used when p4type is P4_INT64 */
- double *pReal; /* Used when p4type is P4_REAL */
- FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
- sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
- CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
- Mem *pMem; /* Used when p4type is P4_MEM */
- VTable *pVtab; /* Used when p4type is P4_VTAB */
- KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
- int *ai; /* Used when p4type is P4_INTARRAY */
- SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
- Table *pTab; /* Used when p4type is P4_TABLE */
-#ifdef SQLITE_ENABLE_CURSOR_HINTS
- Expr *pExpr; /* Used when p4type is P4_EXPR */
-#endif
- int (*xAdvance)(BtCursor *, int);
- } p4;
-#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
- char *zComment; /* Comment to improve readability */
-#endif
-#ifdef VDBE_PROFILE
- u32 cnt; /* Number of times this instruction was executed */
- u64 cycles; /* Total time spent executing this instruction */
-#endif
-#ifdef SQLITE_VDBE_COVERAGE
- u32 iSrcLine; /* Source-code line that generated this opcode
- ** with flags in the upper 8 bits */
-#endif
-};
-typedef struct VdbeOp VdbeOp;
-
-
-/*
-** A sub-routine used to implement a trigger program.
-*/
-struct SubProgram {
- VdbeOp *aOp; /* Array of opcodes for sub-program */
- int nOp; /* Elements in aOp[] */
- int nMem; /* Number of memory cells required */
- int nCsr; /* Number of cursors required */
- u8 *aOnce; /* Array of OP_Once flags */
- void *token; /* id that may be used to recursive triggers */
- SubProgram *pNext; /* Next sub-program already visited */
-};
-
-/*
-** A smaller version of VdbeOp used for the VdbeAddOpList() function because
-** it takes up less space.
-*/
-struct VdbeOpList {
- u8 opcode; /* What operation to perform */
- signed char p1; /* First operand */
- signed char p2; /* Second parameter (often the jump destination) */
- signed char p3; /* Third parameter */
-};
-typedef struct VdbeOpList VdbeOpList;
-
-/*
-** Allowed values of VdbeOp.p4type
-*/
-#define P4_NOTUSED 0 /* The P4 parameter is not used */
-#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
-#define P4_STATIC (-1) /* Pointer to a static string */
-#define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
-#define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
-#define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
-#define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
-#define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
-/* Above do not own any resources. Must free those below */
-#define P4_FREE_IF_LE (-7)
-#define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
-#define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
-#define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
-#define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
-#define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
-#define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
-#define P4_REAL (-13) /* P4 is a 64-bit floating point value */
-#define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
-#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
-#define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
-#define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
-
-/* Error message codes for OP_Halt */
-#define P5_ConstraintNotNull 1
-#define P5_ConstraintUnique 2
-#define P5_ConstraintCheck 3
-#define P5_ConstraintFK 4
-
-/*
-** 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
-#ifdef 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
-
-/*
-** The following macro converts a label returned by sqlite3VdbeMakeLabel()
-** into an index into the Parse.aLabel[] array that contains the resolved
-** address of that label.
-*/
-#define ADDR(X) (~(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 in the middle of vdbe.h ********************/
-/************** Begin file opcodes.h *****************************************/
-/* Automatically generated. Do not edit */
-/* See the tool/mkopcodeh.tcl script for details */
-#define OP_Savepoint 0
-#define OP_AutoCommit 1
-#define OP_Transaction 2
-#define OP_SorterNext 3 /* jump */
-#define OP_Prev 4 /* jump */
-#define OP_Next 5 /* jump */
-#define OP_Checkpoint 6
-#define OP_JournalMode 7
-#define OP_Vacuum 8
-#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
-#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
-#define OP_Goto 11 /* jump */
-#define OP_Gosub 12 /* jump */
-#define OP_InitCoroutine 13 /* jump */
-#define OP_Yield 14 /* jump */
-#define OP_MustBeInt 15 /* jump */
-#define OP_Jump 16 /* jump */
-#define OP_Once 17 /* jump */
-#define OP_If 18 /* jump */
-#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
-#define OP_IfNot 20 /* jump */
-#define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
-#define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
-#define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
-#define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
-#define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
-#define OP_IfNoHope 26 /* jump, synopsis: key=r[P3@P4] */
-#define OP_NoConflict 27 /* jump, synopsis: key=r[P3@P4] */
-#define OP_NotFound 28 /* jump, synopsis: key=r[P3@P4] */
-#define OP_Found 29 /* jump, synopsis: key=r[P3@P4] */
-#define OP_SeekRowid 30 /* jump, synopsis: intkey=r[P3] */
-#define OP_NotExists 31 /* jump, synopsis: intkey=r[P3] */
-#define OP_Last 32 /* jump */
-#define OP_IfSmaller 33 /* jump */
-#define OP_SorterSort 34 /* jump */
-#define OP_Sort 35 /* jump */
-#define OP_Rewind 36 /* jump */
-#define OP_IdxLE 37 /* jump, synopsis: key=r[P3@P4] */
-#define OP_IdxGT 38 /* jump, synopsis: key=r[P3@P4] */
-#define OP_IdxLT 39 /* jump, synopsis: key=r[P3@P4] */
-#define OP_IdxGE 40 /* jump, synopsis: key=r[P3@P4] */
-#define OP_RowSetRead 41 /* jump, synopsis: r[P3]=rowset(P1) */
-#define OP_RowSetTest 42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
-#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
-#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
-#define OP_Program 45 /* jump */
-#define OP_FkIfZero 46 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
-#define OP_IfPos 47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
-#define OP_IfNotZero 48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
-#define OP_DecrJumpZero 49 /* jump, synopsis: if (--r[P1])==0 goto P2 */
-#define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
-#define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
-#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
-#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
-#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
-#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
-#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]=r[P1] */
-#define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
-#define OP_IncrVacuum 59 /* jump */
-#define OP_VNext 60 /* jump */
-#define OP_Init 61 /* jump, synopsis: Start at P2 */
-#define OP_PureFunc0 62
-#define OP_Function0 63 /* synopsis: r[P3]=func(r[P2@P5]) */
-#define OP_PureFunc 64
-#define OP_Function 65 /* synopsis: r[P3]=func(r[P2@P5]) */
-#define OP_Return 66
-#define OP_EndCoroutine 67
-#define OP_HaltIfNull 68 /* synopsis: if r[P3]=null halt */
-#define OP_Halt 69
-#define OP_Integer 70 /* synopsis: r[P2]=P1 */
-#define OP_Int64 71 /* synopsis: r[P2]=P4 */
-#define OP_String 72 /* synopsis: r[P2]='P4' (len=P1) */
-#define OP_Null 73 /* synopsis: r[P2..P3]=NULL */
-#define OP_SoftNull 74 /* synopsis: r[P1]=NULL */
-#define OP_Blob 75 /* synopsis: r[P2]=P4 (len=P1) */
-#define OP_Variable 76 /* synopsis: r[P2]=parameter(P1,P4) */
-#define OP_Move 77 /* synopsis: r[P2@P3]=r[P1@P3] */
-#define OP_Copy 78 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
-#define OP_SCopy 79 /* synopsis: r[P2]=r[P1] */
-#define OP_IntCopy 80 /* synopsis: r[P2]=r[P1] */
-#define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */
-#define OP_CollSeq 82
-#define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */
-#define OP_RealAffinity 84
-#define OP_Cast 85 /* synopsis: affinity(r[P1]) */
-#define OP_Permutation 86
-#define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */
-#define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
-#define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */
-#define OP_Column 90 /* synopsis: r[P3]=PX */
-#define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */
-#define OP_MakeRecord 92 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
-#define OP_Count 93 /* synopsis: r[P2]=count() */
-#define OP_ReadCookie 94
-#define OP_SetCookie 95
-#define OP_BitAnd 96 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
-#define OP_BitOr 97 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
-#define OP_ShiftLeft 98 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<>r[P1] */
-#define OP_Add 100 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
-#define OP_Subtract 101 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
-#define OP_Multiply 102 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
-#define OP_Divide 103 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
-#define OP_Remainder 104 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
-#define OP_Concat 105 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
-#define OP_ReopenIdx 106 /* synopsis: root=P2 iDb=P3 */
-#define OP_BitNot 107 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
-#define OP_OpenRead 108 /* synopsis: root=P2 iDb=P3 */
-#define OP_OpenWrite 109 /* synopsis: root=P2 iDb=P3 */
-#define OP_String8 110 /* same as TK_STRING, synopsis: r[P2]='P4' */
-#define OP_OpenDup 111
-#define OP_OpenAutoindex 112 /* synopsis: nColumn=P2 */
-#define OP_OpenEphemeral 113 /* synopsis: nColumn=P2 */
-#define OP_SorterOpen 114
-#define OP_SequenceTest 115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
-#define OP_OpenPseudo 116 /* synopsis: P3 columns in r[P2] */
-#define OP_Close 117
-#define OP_ColumnsUsed 118
-#define OP_SeekHit 119 /* synopsis: seekHit=P2 */
-#define OP_Sequence 120 /* synopsis: r[P2]=cursor[P1].ctr++ */
-#define OP_NewRowid 121 /* synopsis: r[P2]=rowid */
-#define OP_Insert 122 /* synopsis: intkey=r[P3] data=r[P2] */
-#define OP_Delete 123
-#define OP_ResetCount 124
-#define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
-#define OP_SorterData 126 /* synopsis: r[P2]=data */
-#define OP_RowData 127 /* synopsis: r[P2]=data */
-#define OP_Rowid 128 /* synopsis: r[P2]=rowid */
-#define OP_NullRow 129
-#define OP_SeekEnd 130
-#define OP_SorterInsert 131 /* synopsis: key=r[P2] */
-#define OP_IdxInsert 132 /* synopsis: key=r[P2] */
-#define OP_IdxDelete 133 /* synopsis: key=r[P2@P3] */
-#define OP_DeferredSeek 134 /* synopsis: Move P3 to P1.rowid if needed */
-#define OP_IdxRowid 135 /* synopsis: r[P2]=rowid */
-#define OP_Destroy 136
-#define OP_Clear 137
-#define OP_ResetSorter 138
-#define OP_CreateBtree 139 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
-#define OP_SqlExec 140
-#define OP_ParseSchema 141
-#define OP_LoadAnalysis 142
-#define OP_DropTable 143
-#define OP_DropIndex 144
-#define OP_Real 145 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
-#define OP_DropTrigger 146
-#define OP_IntegrityCk 147
-#define OP_RowSetAdd 148 /* synopsis: rowset(P1)=r[P2] */
-#define OP_Param 149
-#define OP_FkCounter 150 /* synopsis: fkctr[P1]+=P2 */
-#define OP_MemMax 151 /* synopsis: r[P1]=max(r[P1],r[P2]) */
-#define OP_OffsetLimit 152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
-#define OP_AggInverse 153 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
-#define OP_AggStep 154 /* synopsis: accum=r[P3] step(r[P2@P5]) */
-#define OP_AggStep1 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
-#define OP_AggValue 156 /* synopsis: r[P3]=value N=P2 */
-#define OP_AggFinal 157 /* synopsis: accum=r[P1] N=P2 */
-#define OP_Expire 158
-#define OP_TableLock 159 /* synopsis: iDb=P1 root=P2 write=P3 */
-#define OP_VBegin 160
-#define OP_VCreate 161
-#define OP_VDestroy 162
-#define OP_VOpen 163
-#define OP_VColumn 164 /* synopsis: r[P3]=vcolumn(P2) */
-#define OP_VRename 165
-#define OP_Pagecount 166
-#define OP_MaxPgcnt 167
-#define OP_Trace 168
-#define OP_CursorHint 169
-#define OP_Noop 170
-#define OP_Explain 171
-#define OP_Abortable 172
-
-/* 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 0x01 /* jump: P2 holds jmp target */
-#define OPFLG_IN1 0x02 /* in1: P1 is an input */
-#define OPFLG_IN2 0x04 /* in2: P2 is an input */
-#define OPFLG_IN3 0x08 /* in3: P3 is an input */
-#define OPFLG_OUT2 0x10 /* out2: P2 is an output */
-#define OPFLG_OUT3 0x20 /* out3: P3 is an output */
-#define OPFLG_INITIALIZER {\
-/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
-/* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
-/* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
-/* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
-/* 32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
-/* 40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
-/* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
-/* 56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
-/* 64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
-/* 72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
-/* 80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
-/* 88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
-/* 96 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
-/* 104 */ 0x26, 0x26, 0x00, 0x12, 0x00, 0x00, 0x10, 0x00,\
-/* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
-/* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
-/* 144 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
-/* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
-/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00,}
-
-/* The sqlite3P2Values() routine is able to run faster if it knows
-** the value of the largest JUMP opcode. The smaller the maximum
-** JUMP opcode the better, so the mkopcodeh.tcl script that
-** generated this include file strives to group all JUMP opcodes
-** together near the beginning of the list.
-*/
-#define SQLITE_MX_JUMP_OPCODE 61 /* Maximum JUMP opcode */
-
-/************** End of opcodes.h *********************************************/
-/************** Continuing where we left off in vdbe.h ***********************/
-
-/*
-** Additional non-public SQLITE_PREPARE_* flags
-*/
-#define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
-#define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
-
-/*
-** Prototypes for the VDBE interface. See comments on the implementation
-** for a description of what each of these routines does.
-*/
-SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
-SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
-SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
-SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
-SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
-SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
-#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
-SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
-SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
-#else
-# define sqlite3VdbeVerifyNoMallocRequired(A,B)
-# define sqlite3VdbeVerifyNoResultRow(A)
-#endif
-#if defined(SQLITE_DEBUG)
-SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
-#else
-# define sqlite3VdbeVerifyAbortable(A,B)
-#endif
-SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
-#ifndef SQLITE_OMIT_EXPLAIN
-SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
-SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
-SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
-# define ExplainQueryPlan(P) sqlite3VdbeExplain P
-# define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
-# define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
-#else
-# define ExplainQueryPlan(P)
-# define ExplainQueryPlanPop(P)
-# define ExplainQueryPlanParent(P) 0
-# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
-#endif
-#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
-SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
-#else
-# define sqlite3ExplainBreakpoint(A,B) /*no-op*/
-#endif
-SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
-SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
-SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
-SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
-SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
-SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
-SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
-SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
-SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
-SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
-SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
-SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
-SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
-SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
-SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
-SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
-SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
-SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
-#endif
-SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
-SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
-SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
-SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
-SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
-#ifdef SQLITE_ENABLE_NORMALIZE
-SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
-SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
-#endif
-SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
-SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
-SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
-SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
-#ifndef SQLITE_OMIT_TRACE
-SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
-#endif
-SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
-SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
-
-SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
-SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
-SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
-SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
-
-typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
-SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
-
-#ifndef SQLITE_OMIT_TRIGGER
-SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
-#endif
-
-SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
-
-/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
-** each VDBE opcode.
-**
-** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
-** comments in VDBE programs that show key decision points in the code
-** generator.
-*/
-#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
-SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
-# define VdbeComment(X) sqlite3VdbeComment X
-SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
-# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
-# ifdef SQLITE_ENABLE_MODULE_COMMENTS
-# define VdbeModuleComment(X) sqlite3VdbeNoopComment X
-# else
-# define VdbeModuleComment(X)
-# endif
-#else
-# define VdbeComment(X)
-# define VdbeNoopComment(X)
-# define VdbeModuleComment(X)
-#endif
-
-/*
-** The VdbeCoverage macros are used to set a coverage testing point
-** for VDBE branch instructions. The coverage testing points are line
-** numbers in the sqlite3.c source file. VDBE branch coverage testing
-** only works with an amalagmation build. That's ok since a VDBE branch
-** coverage build designed for testing the test suite only. No application
-** should ever ship with VDBE branch coverage measuring turned on.
-**
-** VdbeCoverage(v) // Mark the previously coded instruction
-** // as a branch
-**
-** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
-**
-** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
-**
-** VdbeCoverageNeverTaken(v) // Previous branch is never taken
-**
-** VdbeCoverageNeverNull(v) // Previous three-way branch is only
-** // taken on the first two ways. The
-** // NULL option is not possible
-**
-** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
-** // in distingishing equal and not-equal.
-**
-** Every VDBE branch operation must be tagged with one of the macros above.
-** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
-** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
-** routine in vdbe.c, alerting the developer to the missed tag.
-**
-** During testing, the test application will invoke
-** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
-** routine that is invoked as each bytecode branch is taken. The callback
-** contains the sqlite3.c source line number ov the VdbeCoverage macro and
-** flags to indicate whether or not the branch was taken. The test application
-** is responsible for keeping track of this and reporting byte-code branches
-** that are never taken.
-**
-** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
-** vdbe.c source file for additional information.
-*/
-#ifdef SQLITE_VDBE_COVERAGE
-SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
-# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
-# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
-# define VdbeCoverageAlwaysTaken(v) \
- sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
-# define VdbeCoverageNeverTaken(v) \
- sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
-# define VdbeCoverageNeverNull(v) \
- sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
-# define VdbeCoverageNeverNullIf(v,x) \
- if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
-# define VdbeCoverageEqNe(v) \
- sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
-# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
-#else
-# define VdbeCoverage(v)
-# define VdbeCoverageIf(v,x)
-# define VdbeCoverageAlwaysTaken(v)
-# define VdbeCoverageNeverTaken(v)
-# define VdbeCoverageNeverNull(v)
-# define VdbeCoverageNeverNullIf(v,x)
-# define VdbeCoverageEqNe(v)
-# define VDBE_OFFSET_LINENO(x) 0
-#endif
-
-#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
-SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
-#else
-# define sqlite3VdbeScanStatus(a,b,c,d,e)
-#endif
-
-#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
-SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
-#endif
-
-#endif /* SQLITE_VDBE_H */
-
-/************** End of vdbe.h ************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include pager.h in the middle of sqliteInt.h *****************/
-/************** Begin file pager.h *******************************************/
-/*
-** 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.
-*/
-
-#ifndef SQLITE_PAGER_H
-#define SQLITE_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".
-*/
-#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
- #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))
-
-/*
-** 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_MEMORY 0x0002 /* In-memory database */
-
-/*
-** Valid values for the second argument to sqlite3PagerLockingMode().
-*/
-#define PAGER_LOCKINGMODE_QUERY -1
-#define PAGER_LOCKINGMODE_NORMAL 0
-#define PAGER_LOCKINGMODE_EXCLUSIVE 1
-
-/*
-** Numeric constants that encode the journalmode.
-**
-** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
-** are exposed in the API via the "PRAGMA journal_mode" command and
-** therefore cannot be changed without a compatibility break.
-*/
-#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 */
-
-/*
-** Flags that make up the mask passed to sqlite3PagerGet().
-*/
-#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
-#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
-
-/*
-** Flags for sqlite3PagerSetFlags()
-**
-** Value constraints (enforced via assert()):
-** PAGER_FULLFSYNC == SQLITE_FullFSync
-** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
-** PAGER_CACHE_SPILL == SQLITE_CacheSpill
-*/
-#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
-#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
-#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
-#define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
-#define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
-#define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
-#define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
-#define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
-#define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
-
-/*
-** 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. */
-SQLITE_PRIVATE int sqlite3PagerOpen(
- sqlite3_vfs*,
- Pager **ppPager,
- const char*,
- int,
- int,
- int,
- void(*)(DbPage*)
-);
-SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
-SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
-
-/* Functions used to configure a Pager object. */
-SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
-SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
-#ifdef SQLITE_HAS_CODEC
-SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
-#endif
-SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
-SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
-SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
-SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
-SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
-SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
-SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
-SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
-SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
-SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
-SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
-
-/* Functions used to obtain and release page references. */
-SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
-SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
-SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
-
-/* Operations on page references. */
-SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
-SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
-SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
-SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
-SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
-
-/* Functions used to manage pager transactions and savepoints. */
-SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
-SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
-SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
-SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
-SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
-SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
-SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
-SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
-
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
-SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
-SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
-SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
-SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
-# ifdef SQLITE_ENABLE_SNAPSHOT
-SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
-SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
-SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
-SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
-SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
-# endif
-#endif
-
-#ifdef SQLITE_DIRECT_OVERFLOW_READ
-SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
-#endif
-
-#ifdef SQLITE_ENABLE_ZIPVFS
-SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
-#endif
-
-/* Functions used to query pager state and configuration. */
-SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
-SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
-#endif
-SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
-SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
-SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
-SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
-SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
-SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
-SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
-SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
-SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
-SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
-#else
-# define sqlite3PagerResetLockTimeout(X)
-#endif
-
-/* Functions used to truncate the database file. */
-SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
-
-SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
-
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
-SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
-#endif
-
-/* Functions to support testing and debugging. */
-#if !defined(NDEBUG) || defined(SQLITE_TEST)
-SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
-SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
-#endif
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
-SQLITE_PRIVATE 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
-
-#endif /* SQLITE_PAGER_H */
-
-/************** End of pager.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include pcache.h in the middle of sqliteInt.h ****************/
-/************** Begin file pcache.h ******************************************/
-/*
-** 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.
-*/
-
-#ifndef _PCACHE_H_
-
-typedef struct PgHdr PgHdr;
-typedef struct PCache PCache;
-
-/*
-** Every page in the cache is controlled by an instance of the following
-** structure.
-*/
-struct PgHdr {
- sqlite3_pcache_page *pPage; /* Pcache object page handle */
- void *pData; /* Page data */
- void *pExtra; /* Extra content */
- PCache *pCache; /* PRIVATE: Cache that owns this page */
- PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
- Pager *pPager; /* The pager this page is part of */
- Pgno pgno; /* Page number for this page */
-#ifdef SQLITE_CHECK_PAGES
- u32 pageHash; /* Hash of page content */
-#endif
- u16 flags; /* PGHDR flags defined below */
-
- /**********************************************************************
- ** Elements above, except pCache, are public. All that follow are
- ** private to pcache.c and should not be accessed by other modules.
- ** pCache is grouped with the public elements for efficiency.
- */
- i16 nRef; /* Number of users of this page */
- PgHdr *pDirtyNext; /* Next element in list of dirty pages */
- PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
- /* NB: pDirtyNext and pDirtyPrev are undefined if the
- ** PgHdr object is not dirty */
-};
-
-/* Bit values for PgHdr.flags */
-#define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
-#define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
-#define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
-#define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
- ** writing this page to the database */
-#define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
-#define PGHDR_MMAP 0x020 /* This is an mmap page object */
-
-#define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
-
-/* Initialize and shutdown the page cache subsystem */
-SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
-SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
-
-/* Page cache buffer management:
-** These routines implement SQLITE_CONFIG_PAGECACHE.
-*/
-SQLITE_PRIVATE 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.
-*/
-SQLITE_PRIVATE int 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. */
-SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
-
-/* Return the size in bytes of a PCache object. Used to preallocate
-** storage space.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSize(void);
-
-/* One release per successful fetch. Page is pinned until released.
-** Reference counted.
-*/
-SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
-SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
-SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
-SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
-
-SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
-SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
-SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
-SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
-SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
-
-/* Change a page number. Used by incr-vacuum. */
-SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
-
-/* Remove all pages with pgno>x. Reset the cache if x==0 */
-SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
-
-/* Get a list of all dirty pages in the cache, sorted by page number */
-SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
-
-/* Reset and close the cache object */
-SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
-
-/* Clear flags from pages of the page cache */
-SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
-
-/* Discard the contents of the cache */
-SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
-
-/* Return the total number of outstanding page references */
-SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
-
-/* Increment the reference count of an existing page */
-SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
-
-SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
-
-/* Return the total number of pages stored in the cache */
-SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
-
-#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
-/* 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.
-*/
-SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
-#endif
-
-#if defined(SQLITE_DEBUG)
-/* Check invariants on a PgHdr object */
-SQLITE_PRIVATE int sqlite3PcachePageSanity(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.
-*/
-SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
-#endif
-
-/* Set or get the suggested spill-size for the specified pager-cache.
-**
-** The spill-size is the minimum number of pages in cache before the cache
-** will attempt to spill dirty pages by calling xStress.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
-
-/* Free up as much memory as possible from the page cache */
-SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
-
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
-/* Try to return memory used by the pcache module to the main memory heap */
-SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
-#endif
-
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
-#endif
-
-SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
-
-/* Return the header size */
-SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
-SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
-
-/* Number of dirty pages as a percentage of the configured cache size */
-SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
-
-#ifdef SQLITE_DIRECT_OVERFLOW_READ
-SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
-#endif
-
-#endif /* _PCACHE_H_ */
-
-/************** End of pcache.h **********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include os.h in the middle of sqliteInt.h ********************/
-/************** Begin file os.h **********************************************/
-/*
-** 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.
-*/
-#ifndef _SQLITE_OS_H_
-#define _SQLITE_OS_H_
-
-/*
-** Attempt to automatically detect the operating system and setup the
-** necessary pre-processor macros for it.
-*/
-/************** Include os_setup.h in the middle of os.h *********************/
-/************** Begin file os_setup.h ****************************************/
-/*
-** 2013 November 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 pre-processor directives related to operating system
-** detection and/or setup.
-*/
-#ifndef SQLITE_OS_SETUP_H
-#define SQLITE_OS_SETUP_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, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
-** the three will be 1. The other two will be 0.
-*/
-#if defined(SQLITE_OS_OTHER)
-# if SQLITE_OS_OTHER==1
-# undef SQLITE_OS_UNIX
-# define SQLITE_OS_UNIX 0
-# undef SQLITE_OS_WIN
-# define SQLITE_OS_WIN 0
-# else
-# undef SQLITE_OS_OTHER
-# endif
-#endif
-#if !defined(SQLITE_OS_UNIX) && !defined(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
-# else
-# define SQLITE_OS_WIN 0
-# define SQLITE_OS_UNIX 1
-# endif
-# else
-# define SQLITE_OS_UNIX 0
-# endif
-#else
-# ifndef SQLITE_OS_WIN
-# define SQLITE_OS_WIN 0
-# endif
-#endif
-
-#endif /* SQLITE_OS_SETUP_H */
-
-/************** End of os_setup.h ********************************************/
-/************** Continuing where we left off in os.h *************************/
-
-/* If the SET_FULLSYNC macro is not defined above, then make it
-** a no-op
-*/
-#ifndef SET_FULLSYNC
-# define SET_FULLSYNC(x,y)
-#endif
-
-/*
-** The default size of a disk sector
-*/
-#ifndef SQLITE_DEFAULT_SECTOR_SIZE
-# define SQLITE_DEFAULT_SECTOR_SIZE 4096
-#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.
-*/
-#ifndef SQLITE_TEMP_FILE_PREFIX
-# 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().
-*/
-#define NO_LOCK 0
-#define SHARED_LOCK 1
-#define RESERVED_LOCK 2
-#define PENDING_LOCK 3
-#define 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 possibility 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.
-**
-*/
-#ifdef SQLITE_OMIT_WSD
-# define PENDING_BYTE (0x40000000)
-#else
-# define PENDING_BYTE sqlite3PendingByte
-#endif
-#define RESERVED_BYTE (PENDING_BYTE+1)
-#define SHARED_FIRST (PENDING_BYTE+2)
-#define SHARED_SIZE 510
-
-/*
-** Wrapper around OS specific sqlite3_os_init() function.
-*/
-SQLITE_PRIVATE int sqlite3OsInit(void);
-
-/*
-** Functions for accessing sqlite3_file methods
-*/
-SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
-SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
-SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
-SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
-SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
-SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
-SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
-SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
-SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
-#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
-SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
-SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
-SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
-SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
-SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
-#endif /* SQLITE_OMIT_WAL */
-SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
-SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
-
-
-/*
-** Functions for accessing sqlite3_vfs methods
-*/
-SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
-SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
-SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
-SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
-SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
-SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
-SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
-#endif /* SQLITE_OMIT_LOAD_EXTENSION */
-SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
-SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
-SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
-SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
-
-/*
-** Convenience functions for opening and closing files using
-** sqlite3_malloc() to obtain space for the file-handle structure.
-*/
-SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
-SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
-
-#endif /* _SQLITE_OS_H_ */
-
-/************** End of os.h **************************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include mutex.h in the middle of sqliteInt.h *****************/
-/************** Begin file mutex.h *******************************************/
-/*
-** 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.
-*/
-
-
-/*
-** Figure out what version of the code to use. The choices are
-**
-** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
-** mutexes implementation 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.
-*/
-#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
-# else
-# define SQLITE_MUTEX_NOOP
-# endif
-#endif
-
-#ifdef SQLITE_MUTEX_OMIT
-/*
-** If this is a no-op implementation, implement everything as macros.
-*/
-#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
-#define sqlite3_mutex_free(X)
-#define sqlite3_mutex_enter(X)
-#define sqlite3_mutex_try(X) SQLITE_OK
-#define sqlite3_mutex_leave(X)
-#define sqlite3_mutex_held(X) ((void)(X),1)
-#define sqlite3_mutex_notheld(X) ((void)(X),1)
-#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
-#define sqlite3MutexInit() SQLITE_OK
-#define sqlite3MutexEnd()
-#define MUTEX_LOGIC(X)
-#else
-#define MUTEX_LOGIC(X) X
-#endif /* defined(SQLITE_MUTEX_OMIT) */
-
-/************** End of mutex.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
-
-/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
-** synchronous setting to EXTRA. It is no longer supported.
-*/
-#ifdef SQLITE_EXTRA_DURABLE
-# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
-# define SQLITE_DEFAULT_SYNCHRONOUS 3
-#endif
-
-/*
-** Default synchronous levels.
-**
-** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
-** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
-**
-** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
-** OFF 1 0
-** NORMAL 2 1
-** FULL 3 2
-** EXTRA 4 3
-**
-** The "PRAGMA synchronous" statement also uses the zero-based numbers.
-** In other words, the zero-based numbers are used for all external interfaces
-** and the one-based values are used internally.
-*/
-#ifndef SQLITE_DEFAULT_SYNCHRONOUS
-# define SQLITE_DEFAULT_SYNCHRONOUS 2
-#endif
-#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
-# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
-#endif
-
-/*
-** 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.
-*/
-struct Db {
- char *zDbSName; /* Name of this database. (schema name, not filename) */
- Btree *pBt; /* The B*Tree structure for this database file */
- u8 safety_level; /* How aggressive at syncing data to disk */
- u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
- 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.
-*/
-struct Schema {
- int schema_cookie; /* Database schema version number for this file */
- int iGeneration; /* Generation counter. Incremented with each change */
- Hash tblHash; /* All tables indexed by name */
- Hash idxHash; /* All (named) indices indexed by name */
- Hash trigHash; /* All triggers indexed by name */
- Hash fkeyHash; /* All foreign keys by referenced table name */
- Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
- u8 file_format; /* Schema format version for this file */
- u8 enc; /* Text encoding used by this database */
- u16 schemaFlags; /* Flags associated with this schema */
- int cache_size; /* Number of pages to use in the cache */
-};
-
-/*
-** 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->schemaFlags&(P))==(P))
-#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
-#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
-#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(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) */
-#define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
-
-/*
-** The number of different kinds of things that can be limited
-** using the sqlite3_limit() interface.
-*/
-#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+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.
-*/
-struct Lookaside {
- u32 bDisable; /* Only operate the lookaside when zero */
- u16 sz; /* Size of each buffer in bytes */
- u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
- u32 nSlot; /* Number of lookaside slots allocated */
- u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
- LookasideSlot *pInit; /* List of buffers not previously used */
- LookasideSlot *pFree; /* List of available buffers */
- void *pStart; /* First byte of available memory space */
- void *pEnd; /* First byte past end of available space */
-};
-struct LookasideSlot {
- LookasideSlot *pNext; /* Next buffer in the list of free buffers */
-};
-
-/*
-** A hash table for built-in function definitions. (Application-defined
-** functions use a regular table table from hash.h.)
-**
-** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
-** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
-** macro to compute a hash on the function name.
-*/
-#define SQLITE_FUNC_HASH_SZ 23
-struct FuncDefHash {
- FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
-};
-#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
-
-#ifdef SQLITE_USER_AUTHENTICATION
-/*
-** Information held in the "sqlite3" database connection object and used
-** to manage user authentication.
-*/
-typedef struct sqlite3_userauth sqlite3_userauth;
-struct sqlite3_userauth {
- u8 authLevel; /* Current authentication level */
- int nAuthPW; /* Size of the zAuthPW in bytes */
- char *zAuthPW; /* Password used to authenticate */
- char *zAuthUser; /* User name used to authenticate */
-};
-
-/* Allowed values for sqlite3_userauth.authLevel */
-#define UAUTH_Unknown 0 /* Authentication not yet checked */
-#define UAUTH_Fail 1 /* User authentication failed */
-#define UAUTH_User 2 /* Authenticated as a normal user */
-#define UAUTH_Admin 3 /* Authenticated as an administrator */
-
-/* Functions used only by user authorization logic */
-SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
-SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
-SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
-SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
-
-#endif /* SQLITE_USER_AUTHENTICATION */
-
-/*
-** typedef for the authorization callback function.
-*/
-#ifdef SQLITE_USER_AUTHENTICATION
- typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
- const char*, const char*);
-#else
- typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
- const char*);
-#endif
-
-#ifndef SQLITE_OMIT_DEPRECATED
-/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
-** in the style of sqlite3_trace()
-*/
-#define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
-#define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
-#else
-#define SQLITE_TRACE_LEGACY 0
-#define SQLITE_TRACE_XPROFILE 0
-#endif /* SQLITE_OMIT_DEPRECATED */
-#define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
-
-
-/*
-** Each database connection is an instance of the following structure.
-*/
-struct sqlite3 {
- sqlite3_vfs *pVfs; /* OS Interface */
- struct Vdbe *pVdbe; /* List of active virtual machines */
- CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
- sqlite3_mutex *mutex; /* Connection mutex */
- Db *aDb; /* All backends */
- int nDb; /* Number of backends currently in use */
- u32 mDbFlags; /* flags recording internal state */
- u64 flags; /* flags settable by pragmas. See below */
- i64 lastRowid; /* ROWID of most recent insert (see above) */
- i64 szMmap; /* Default mmap_size setting */
- u32 nSchemaLock; /* Do not reset the schema when non-zero */
- unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
- int errCode; /* Most recent error code (SQLITE_*) */
- int errMask; /* & result codes with this before returning */
- int iSysErrno; /* Errno value from last system error */
- u16 dbOptFlags; /* Flags to enable/disable optimizations */
- u8 enc; /* Text encoding */
- u8 autoCommit; /* The auto-commit flag. */
- u8 temp_store; /* 1: file 2: memory 0: default */
- u8 mallocFailed; /* True if we have seen a malloc failure */
- u8 bBenignMalloc; /* Do not require OOMs if true */
- u8 dfltLockMode; /* Default locking-mode for attached dbs */
- signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
- u8 suppressErr; /* Do not issue error messages if true */
- u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
- u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
- u8 mTrace; /* zero or more SQLITE_TRACE flags */
- u8 noSharedCache; /* True if no shared-cache backends */
- u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
- int nextPagesize; /* Pagesize after VACUUM if >0 */
- u32 magic; /* Magic number for detect library misuse */
- int nChange; /* Value returned by sqlite3_changes() */
- int nTotalChange; /* Value returned by sqlite3_total_changes() */
- int aLimit[SQLITE_N_LIMIT]; /* Limits */
- int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
- struct sqlite3InitInfo { /* Information used during initialization */
- int newTnum; /* Rootpage of table being initialized */
- u8 iDb; /* Which db file is being initialized */
- u8 busy; /* TRUE if currently initializing */
- unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
- unsigned imposterTable : 1; /* Building an imposter table */
- unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
- } init;
- int nVdbeActive; /* Number of VDBEs currently running */
- int nVdbeRead; /* Number of active VDBEs that read or write */
- int nVdbeWrite; /* Number of active VDBEs that read and write */
- int nVdbeExec; /* Number of nested calls to VdbeExec() */
- int nVDestroy; /* Number of active OP_VDestroy operations */
- int nExtension; /* Number of loaded extensions */
- void **aExtension; /* Array of shared library handles */
- int (*xTrace)(u32,void*,void*,void*); /* Trace function */
- void *pTraceArg; /* Argument to the trace function */
-#ifndef SQLITE_OMIT_DEPRECATED
- void (*xProfile)(void*,const char*,u64); /* Profiling function */
- void *pProfileArg; /* Argument to profile function */
-#endif
- void *pCommitArg; /* Argument to xCommitCallback() */
- int (*xCommitCallback)(void*); /* Invoked at every commit. */
- void *pRollbackArg; /* Argument to xRollbackCallback() */
- void (*xRollbackCallback)(void*); /* Invoked at every commit. */
- void *pUpdateArg;
- void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
- Parse *pParse; /* Current parse */
-#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
- void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
- void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
- void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
- );
- PreUpdate *pPreUpdate; /* Context for active pre-update callback */
-#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
-#ifndef SQLITE_OMIT_WAL
- int (*xWalCallback)(void *, sqlite3 *, const char *, int);
- void *pWalArg;
-#endif
- void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
- void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
- void *pCollNeededArg;
- sqlite3_value *pErr; /* Most recent error message */
- union {
- volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
- double notUsed1; /* Spacer */
- } u1;
- Lookaside lookaside; /* Lookaside malloc configuration */
-#ifndef SQLITE_OMIT_AUTHORIZATION
- sqlite3_xauth xAuth; /* Access authorization function */
- void *pAuthArg; /* 1st argument to the access auth function */
-#endif
-#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
- int (*xProgress)(void *); /* The progress callback */
- void *pProgressArg; /* Argument to the progress callback */
- unsigned nProgressOps; /* Number of opcodes for progress callback */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- int nVTrans; /* Allocated size of aVTrans */
- Hash aModule; /* populated by sqlite3_create_module() */
- VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
- VTable **aVTrans; /* Virtual tables with open transactions */
- VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
-#endif
- Hash aFunc; /* Hash table of connection functions */
- Hash aCollSeq; /* All collating sequences */
- BusyHandler busyHandler; /* Busy callback */
- Db aDbStatic[2]; /* Static space for the 2 default backends */
- Savepoint *pSavepoint; /* List of active savepoints */
- int busyTimeout; /* Busy handler timeout, in msec */
- int nSavepoint; /* Number of non-transaction savepoints */
- int nStatement; /* Number of nested statement-transactions */
- i64 nDeferredCons; /* Net deferred constraints this transaction. */
- i64 nDeferredImmCons; /* Net deferred immediate constraints */
- int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
-#ifdef 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
-#ifdef SQLITE_USER_AUTHENTICATION
- sqlite3_userauth auth; /* User authentication information */
-#endif
-};
-
-/*
-** A macro to discover the encoding of a database.
-*/
-#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
-#define ENC(db) ((db)->enc)
-
-/*
-** Possible values for the sqlite3.flags.
-**
-** Value constraints (enforced via assert()):
-** SQLITE_FullFSync == PAGER_FULLFSYNC
-** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
-** SQLITE_CacheSpill == PAGER_CACHE_SPILL
-*/
-#define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
-#define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
-#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
-#define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
-#define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
-#define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
-#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
-#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
- /* DELETE, or UPDATE and return */
- /* the count using a callback. */
-#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
- /* result set is empty */
-#define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
-#define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
-#define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
-#define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
-#define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
-#define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
-#define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
-#define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
-#define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
-#define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
-#define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
-#define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
-#define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
-#define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
-#define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
-#define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
-#define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
-#define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
-#define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
-#define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
-#define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
-#define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
-
-/* Flags used only if debugging */
-#define HI(X) ((u64)(X)<<32)
-#ifdef SQLITE_DEBUG
-#define SQLITE_SqlTrace HI(0x0001) /* Debug print SQL as it executes */
-#define SQLITE_VdbeListing HI(0x0002) /* Debug listings of VDBE progs */
-#define SQLITE_VdbeTrace HI(0x0004) /* True to trace VDBE execution */
-#define SQLITE_VdbeAddopTrace HI(0x0008) /* Trace sqlite3VdbeAddOp() calls */
-#define SQLITE_VdbeEQP HI(0x0010) /* Debug EXPLAIN QUERY PLAN */
-#define SQLITE_ParserTrace HI(0x0020) /* PRAGMA parser_trace=ON */
-#endif
-
-/*
-** Allowed values for sqlite3.mDbFlags
-*/
-#define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
-#define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
-#define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
-#define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
-#define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
-
-/*
-** Bits of the sqlite3.dbOptFlags field that are used by the
-** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
-** selectively disable various optimizations.
-*/
-#define SQLITE_QueryFlattener 0x0001 /* Query flattening */
-#define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */
-#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
-#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
-#define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
-#define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
-#define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
-#define SQLITE_Transitive 0x0080 /* Transitive constraints */
-#define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
-#define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
-#define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
-#define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
- /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
-#define SQLITE_PushDown 0x1000 /* The push-down optimization */
-#define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
-#define SQLITE_SkipScan 0x4000 /* Skip-scans */
-#define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
-#define SQLITE_AllOpts 0xffff /* All optimizations */
-
-/*
-** Macros for testing whether or not optimizations are enabled or disabled.
-*/
-#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
-#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
-
-/*
-** Return true if it OK to factor constant expressions into the initialization
-** code. The argument is a Parse object for the code generator.
-*/
-#define ConstFactorOk(P) ((P)->okConstFactor)
-
-/*
-** 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.
-*/
-#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
-#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
-#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
-#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
-#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
-#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
-
-/*
-** Each SQL function is defined by an instance of the following
-** structure. For global built-in functions (ex: substr(), max(), count())
-** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
-** For per-connection application-defined functions, a pointer to this
-** structure is held in the db->aHash hash table.
-**
-** The u.pHash field is used by the global built-ins. The u.pDestructor
-** field is used by per-connection app-def functions.
-*/
-struct FuncDef {
- i8 nArg; /* Number of arguments. -1 means unlimited */
- u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
- void *pUserData; /* User data parameter */
- FuncDef *pNext; /* Next function with same name */
- void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
- void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
- void (*xValue)(sqlite3_context*); /* Current agg value */
- void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
- const char *zName; /* SQL name of the function. */
- union {
- FuncDef *pHash; /* Next with a different name but the same hash */
- FuncDestructor *pDestructor; /* Reference counted destructor function */
- } u;
-};
-
-/*
-** 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;
-};
-
-/*
-** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
-** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
-** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
-** are assert() statements in the code to verify this.
-**
-** Value constraints (enforced via assert()):
-** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
-** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
-** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
-** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
-** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
-*/
-#define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
-#define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
-#define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
-#define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
-#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
-#define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
-#define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
-#define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
-#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
-#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
-#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
-#define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
-#define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
- ** single query - might change over time */
-#define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
-#define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
-#define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
-#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
-
-/*
-** 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.
-**
-** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
-** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
-**
-** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
-** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
-** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
-** and functions like sqlite_version() that can change, but not during
-** a single query. The iArg is ignored. The user-data is always set
-** to a NULL pointer. The bNC parameter is not used.
-**
-** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
-** Used for "pure" date/time functions, this macro is like DFUNCTION
-** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
-** ignored and the user-data for these functions is set to an
-** arbitrary non-NULL pointer. The bNC parameter is not used.
-**
-** 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().
-**
-** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
-** 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_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
-#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
- {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
-#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
- {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
- 0, 0, xFunc, 0, 0, 0, #zName, {0} }
-#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
- {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
- (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
-#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
- {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
-#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
- {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
- pArg, 0, xFunc, 0, 0, 0, #zName, }
-#define LIKEFUNC(zName, nArg, arg, flags) \
- {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
- (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
-#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
- {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
- SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
-#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
- {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
- SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
-#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
- {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
- SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
-#define INTERNAL_FUNCTION(zName, nArg, xFunc) \
- {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
- 0, 0, xFunc, 0, 0, 0, #zName, {0} }
-
-
-/*
-** All current savepoints are stored in a linked list starting at
-** sqlite3.pSavepoint. The first element in the list is the most recently
-** opened savepoint. Savepoints are added to the list by the vdbe
-** OP_Savepoint instruction.
-*/
-struct Savepoint {
- char *zName; /* Savepoint name (nul-terminated) */
- i64 nDeferredCons; /* Number of deferred fk violations */
- i64 nDeferredImmCons; /* Number of deferred imm fk. */
- 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.
-*/
-#define SAVEPOINT_BEGIN 0
-#define SAVEPOINT_RELEASE 1
-#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.
-*/
-struct Module {
- const sqlite3_module *pModule; /* Callback pointers */
- const char *zName; /* Name passed to create_module() */
- void *pAux; /* pAux passed to create_module() */
- void (*xDestroy)(void *); /* Module destructor function */
- Table *pEpoTab; /* Eponymous table for this module */
-};
-
-/*
-** information about each column of an SQL table is held in an instance
-** of this structure.
-*/
-struct Column {
- char *zName; /* Name of this column, \000, then the type */
- Expr *pDflt; /* Default value of this column */
- char *zColl; /* Collating sequence. If NULL, use the default */
- u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
- char affinity; /* One of the SQLITE_AFF_... values */
- u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
- u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
-};
-
-/* Allowed values for Column.colFlags:
-*/
-#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
-#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
-#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
-#define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
-#define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
-
-/*
-** 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.
-**
-** If CollSeq.xCmp is NULL, it means that the
-** collating sequence is undefined. Indices built on an undefined
-** collating sequence may not be read or written.
-*/
-struct CollSeq {
- char *zName; /* Name of the collating sequence, UTF-8 encoded */
- u8 enc; /* Text encoding handled by xCmp() */
- void *pUser; /* First argument to xCmp() */
- int (*xCmp)(void*,int, const void*, int, const void*);
- void (*xDel)(void*); /* Destructor for pUser */
-};
-
-/*
-** A sort order can be either ASC or DESC.
-*/
-#define SQLITE_SO_ASC 0 /* Sort in ascending order */
-#define SQLITE_SO_DESC 1 /* Sort in ascending order */
-#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
-
-/*
-** 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. And the BLOB type is first.
-*/
-#define SQLITE_AFF_BLOB 'A'
-#define SQLITE_AFF_TEXT 'B'
-#define SQLITE_AFF_NUMERIC 'C'
-#define SQLITE_AFF_INTEGER 'D'
-#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.
-*/
-#define SQLITE_AFF_MASK 0x47
-
-/*
-** Additional bit values that can be ORed with an affinity without
-** changing the affinity.
-**
-** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
-** It causes an assert() to fire if either operand to a comparison
-** operator is NULL. It is added to certain comparison operators to
-** prove that the operands are always NOT NULL.
-*/
-#define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
-#define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
-#define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
-#define SQLITE_NULLEQ 0x80 /* NULL=NULL */
-#define SQLITE_NOTNULL 0x90 /* Assert that operands are never 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.
-*/
-struct VTable {
- sqlite3 *db; /* Database connection associated with this table */
- Module *pMod; /* Pointer to module implementation */
- sqlite3_vtab *pVtab; /* Pointer to vtab instance */
- int nRef; /* Number of pointers to this structure */
- u8 bConstraint; /* True if constraints are supported */
- int iSavepoint; /* Depth of the SAVEPOINT stack */
- VTable *pNext; /* Next in linked list (see above) */
-};
-
-/*
-** The schema for each SQL table and view is represented in memory
-** by an instance of the following structure.
-*/
-struct Table {
- char *zName; /* Name of the table or view */
- Column *aCol; /* Information about each column */
- Index *pIndex; /* List of SQL indexes on this table. */
- Select *pSelect; /* NULL for tables. Points to definition if a view. */
- FKey *pFKey; /* Linked list of all foreign keys in this table */
- char *zColAff; /* String defining the affinity of each column */
- ExprList *pCheck; /* All CHECK constraints */
- /* ... also used as column name list in a VIEW */
- int tnum; /* Root BTree page for this table */
- u32 nTabRef; /* Number of pointers to this Table */
- u32 tabFlags; /* Mask of TF_* values */
- i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
- i16 nCol; /* Number of columns in this table */
- LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
- LogEst szTabRow; /* Estimated size of each table row in bytes */
-#ifdef SQLITE_ENABLE_COSTMULT
- LogEst costMult; /* Cost multiplier for using this table */
-#endif
- u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
-#ifndef SQLITE_OMIT_ALTERTABLE
- int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- int nModuleArg; /* Number of arguments to the module */
- char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
- VTable *pVTable; /* List of VTable objects. */
-#endif
- Trigger *pTrigger; /* List of triggers stored in pSchema */
- Schema *pSchema; /* Schema that contains this table */
- Table *pNextZombie; /* Next on the Parse.pZombieTab list */
-};
-
-/*
-** Allowed values for Table.tabFlags.
-**
-** TF_OOOHidden applies to tables or view that have hidden columns that are
-** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
-** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
-** the TF_OOOHidden attribute would apply in this case. Such tables require
-** special handling during INSERT processing.
-*/
-#define TF_Readonly 0x0001 /* Read-only system table */
-#define TF_Ephemeral 0x0002 /* An ephemeral table */
-#define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
-#define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
-#define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
-#define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
-#define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
-#define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
-#define TF_StatsUsed 0x0100 /* Query planner decisions affected by
- ** Index.aiRowLogEst[] values */
-#define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
-#define TF_Shadow 0x0400 /* True for a shadow table */
-
-/*
-** 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.
-*/
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-# define IsVirtual(X) ((X)->nModuleArg)
-#else
-# define IsVirtual(X) 0
-#endif
-
-/*
-** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
-** only works for non-virtual tables (ordinary tables and views) and is
-** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
-** IsHiddenColumn() macro is general purpose.
-*/
-#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
-# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
-# define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
-#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
-# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
-# define IsOrdinaryHiddenColumn(X) 0
-#else
-# define IsHiddenColumn(X) 0
-# define IsOrdinaryHiddenColumn(X) 0
-#endif
-
-
-/* Does the table have a rowid */
-#define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
-#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
-
-/*
-** 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".
-** Equivalent names:
-**
-** from-table == child-table
-** to-table == parent-table
-**
-** 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.
-**
-** The list of all parents for child Table X is held at X.pFKey.
-**
-** A list of all children for a table named Z (which might not even exist)
-** is held in Schema.fkeyHash with a hash key of Z.
-*/
-struct FKey {
- Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
- FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
- char *zTo; /* Name of table that the key points to (aka: Parent) */
- FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
- FKey *pPrevTo; /* Previous with the same zTo */
- int nCol; /* Number of columns in this key */
- /* EV: R-30323-21917 */
- u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
- u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
- Trigger *apTrigger[2];/* Triggers for aAction[] actions */
- struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
- int iFrom; /* Index of column in pFrom */
- char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
- } aCol[1]; /* One entry for each of nCol columns */
-};
-
-/*
-** 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.
-*/
-#define OE_None 0 /* There is no constraint to check */
-#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
-#define OE_Abort 2 /* Back out changes but do no rollback transaction */
-#define OE_Fail 3 /* Stop the operation but leave all prior changes */
-#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
-#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
-#define OE_Update 6 /* Process as a DO UPDATE in an upsert */
-#define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
-#define OE_SetNull 8 /* Set the foreign key value to NULL */
-#define OE_SetDflt 9 /* Set the foreign key value to its default */
-#define OE_Cascade 10 /* Cascade the changes */
-#define OE_Default 11 /* 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.
-**
-** Note that aSortOrder[] and aColl[] have nField+1 slots. There
-** are nField slots for the columns of an index then one extra slot
-** for the rowid at the end.
-*/
-struct KeyInfo {
- u32 nRef; /* Number of references to this KeyInfo object */
- u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
- u16 nKeyField; /* Number of key columns in the index */
- u16 nAllField; /* Total columns, including key plus others */
- sqlite3 *db; /* The database connection */
- u8 *aSortOrder; /* Sort order for each column. */
- CollSeq *aColl[1]; /* Collating sequence for each term of the key */
-};
-
-/*
-** This object holds a record which has been parsed out into individual
-** fields, for the purposes of doing a comparison.
-**
-** 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.
-**
-** An instance of this object serves as a "key" for doing a search on
-** an index b+tree. The goal of the search is to find the entry that
-** is closed to the key described by this object. This object might hold
-** just a prefix of the key. The number of fields is given by
-** pKeyInfo->nField.
-**
-** The r1 and r2 fields are the values to return if this key is less than
-** or greater than a key in the btree, respectively. These are normally
-** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
-** is in DESC order.
-**
-** The key comparison functions actually return default_rc when they find
-** an equals comparison. default_rc can be -1, 0, or +1. If there are
-** multiple entries in the b-tree with the same key (when only looking
-** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
-** cause the search to find the last match, or +1 to cause the search to
-** find the first match.
-**
-** The key comparison functions will set eqSeen to true if they ever
-** get and equal results when comparing this structure to a b-tree record.
-** When default_rc!=0, the search might end up on the record immediately
-** before the first match or immediately after the last match. The
-** eqSeen field will indicate whether or not an exact match exists in the
-** b-tree.
-*/
-struct UnpackedRecord {
- KeyInfo *pKeyInfo; /* Collation and sort-order information */
- Mem *aMem; /* Values */
- u16 nField; /* Number of entries in apMem[] */
- i8 default_rc; /* Comparison result if keys are equal */
- u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
- i8 r1; /* Value to return if (lhs < rhs) */
- i8 r2; /* Value to return if (lhs > rhs) */
- u8 eqSeen; /* True if an equality comparison has been seen */
-};
-
-
-/*
-** 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.
-**
-** While parsing a CREATE TABLE or CREATE INDEX statement in order to
-** generate VDBE code (as opposed to parsing one read from an sqlite_master
-** table as part of parsing an existing database schema), transient instances
-** of this structure may be created. In this case the Index.tnum variable is
-** used to store the address of a VDBE instruction, not a database page
-** number (it cannot - the database page is not allocated until the VDBE
-** program is executed). See convertToWithoutRowidTable() for details.
-*/
-struct Index {
- char *zName; /* Name of this index */
- i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
- LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
- Table *pTable; /* The SQL table being indexed */
- char *zColAff; /* String defining the affinity of each column */
- Index *pNext; /* The next index associated with the same table */
- Schema *pSchema; /* Schema containing this index */
- u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
- const char **azColl; /* Array of collation sequence names for index */
- Expr *pPartIdxWhere; /* WHERE clause for partial indices */
- ExprList *aColExpr; /* Column expressions */
- int tnum; /* DB Page containing root of this index */
- LogEst szIdxRow; /* Estimated average row size in bytes */
- u16 nKeyCol; /* Number of columns forming the key */
- u16 nColumn; /* Number of columns stored in the index */
- u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
- unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
- unsigned bUnordered:1; /* Use this index for == or IN queries only */
- unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
- unsigned isResized:1; /* True if resizeIndexObject() has been called */
- unsigned isCovering:1; /* True if this is a covering index */
- unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
- unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
- unsigned bNoQuery:1; /* Do not use this index to optimize queries */
- unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
-#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
- int nSample; /* Number of elements in aSample[] */
- int nSampleCol; /* Size of IndexSample.anEq[] and so on */
- tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
- IndexSample *aSample; /* Samples of the left-most key */
- tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
- tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
-#endif
- Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
-};
-
-/*
-** Allowed values for Index.idxType
-*/
-#define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
-#define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
-#define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
-#define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
-
-/* Return true if index X is a PRIMARY KEY index */
-#define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
-
-/* Return true if index X is a UNIQUE index */
-#define IsUniqueIndex(X) ((X)->onError!=OE_None)
-
-/* The Index.aiColumn[] values are normally positive integer. But
-** there are some negative values that have special meaning:
-*/
-#define XN_ROWID (-1) /* Indexed column is the rowid */
-#define XN_EXPR (-2) /* Indexed column is an expression */
-
-/*
-** Each sample stored in the sqlite_stat3 table is represented in memory
-** using a structure of this type. See documentation at the top of the
-** analyze.c source file for additional information.
-*/
-struct IndexSample {
- void *p; /* Pointer to sampled record */
- int n; /* Size of record in bytes */
- tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
- tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
- tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
-};
-
-/*
-** Possible values to use within the flags argument to sqlite3GetToken().
-*/
-#define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
-#define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
-
-/*
-** Each token coming out of the lexer is an instance of
-** this structure. Tokens are also used as part of an expression.
-**
-** The memory that "z" points to is owned by other objects. Take care
-** that the owner of the "z" string does not deallocate the string before
-** the Token goes out of scope! Very often, the "z" points to some place
-** in the middle of the Parse.zSql text. But it might also point to a
-** static string.
-*/
-struct Token {
- const char *z; /* Text of the token. Not NULL-terminated! */
- unsigned int n; /* Number of characters in this token */
-};
-
-/*
-** 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.
-*/
-struct AggInfo {
- u8 directMode; /* Direct rendering mode means take data directly
- ** from source tables rather than from accumulators */
- u8 useSortingIdx; /* In direct mode, reference the sorting index rather
- ** than the source table */
- int sortingIdx; /* Cursor number of the sorting index */
- int sortingIdxPTab; /* Cursor number of pseudo-table */
- int nSortingColumn; /* Number of columns in the sorting index */
- int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
- ExprList *pGroupBy; /* The group by clause */
- struct AggInfo_col { /* For each column used in source tables */
- Table *pTab; /* Source table */
- int iTable; /* Cursor number of the source table */
- int iColumn; /* Column number within the source table */
- int iSorterColumn; /* Column number in the sorting index */
- int iMem; /* Memory location that acts as accumulator */
- Expr *pExpr; /* The original expression */
- } *aCol;
- int nColumn; /* Number of used entries in aCol[] */
- int nAccumulator; /* Number of columns that show through to the output.
- ** Additional columns are used only as parameters to
- ** aggregate functions */
- struct AggInfo_func { /* For each aggregate function */
- Expr *pExpr; /* Expression encoding the function */
- FuncDef *pFunc; /* The aggregate function implementation */
- int iMem; /* Memory location that acts as accumulator */
- int iDistinct; /* Ephemeral table used to enforce DISTINCT */
- } *aFunc;
- int nFunc; /* Number of entries in aFunc[] */
-};
-
-/*
-** 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.
-*/
-struct Expr {
- u8 op; /* Operation performed by this node */
- char affinity; /* The affinity of the column or 0 if not a column */
- u32 flags; /* Various flags. EP_* See below */
- union {
- char *zToken; /* Token value. Zero terminated and dequoted */
- int iValue; /* Non-negative integer value if EP_IntValue */
- } 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.
- *********************************************************************/
-
- Expr *pLeft; /* Left subnode */
- Expr *pRight; /* Right subnode */
- union {
- ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
- Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
- } x;
-
- /* If the EP_Reduced 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.
- *********************************************************************/
-
-#if SQLITE_MAX_EXPR_DEPTH>0
- int nHeight; /* Height of the tree headed by this node */
-#endif
- int iTable; /* TK_COLUMN: cursor number of table holding column
- ** TK_REGISTER: register number
- ** TK_TRIGGER: 1 -> new, 0 -> old
- ** EP_Unlikely: 134217728 times likelihood
- ** TK_SELECT: 1st register of result vector */
- ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
- ** TK_VARIABLE: variable number (always >= 1).
- ** TK_SELECT_COLUMN: column of the result vector */
- i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
- i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
- u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
- ** TK_COLUMN: the value of p5 for OP_Column
- ** TK_AGG_FUNCTION: nesting depth */
- AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
- union {
- Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
- ** for a column of an index on an expression */
- Window *pWin; /* TK_FUNCTION: Window definition for the func */
- struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
- int iAddr; /* Subroutine entry address */
- int regReturn; /* Register used to hold return address */
- } sub;
- } y;
-};
-
-/*
-** The following are the meanings of bits in the Expr.flags field.
-** Value restrictions:
-**
-** EP_Agg == NC_HasAgg == SF_HasAgg
-** EP_Win == NC_HasWin
-*/
-#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
-#define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
-#define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
-#define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
-#define EP_Agg 0x000010 /* Contains one or more aggregate functions */
-#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
-#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
-#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
-#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
-#define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
-#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
-#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
-#define EP_Skip 0x001000 /* Operator does not contribute to affinity */
-#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
-#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
-#define EP_Win 0x008000 /* Contains window functions */
-#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
-#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
-#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
-#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
-#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
-#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
-#define EP_Alias 0x400000 /* Is an alias for a result set column */
-#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
-#define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
-#define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
-#define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
-#define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
-#define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
-#define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
-
-/*
-** The EP_Propagate mask is a set of properties that automatically propagate
-** upwards into parent nodes.
-*/
-#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
-
-/*
-** These macros can be used to test, set, or clear bits in the
-** Expr.flags field.
-*/
-#define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
-#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
-#define ExprSetProperty(E,P) (E)->flags|=(P)
-#define ExprClearProperty(E,P) (E)->flags&=~(P)
-#define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
-#define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
-
-/* The ExprSetVVAProperty() macro is used for Verification, Validation,
-** and Accreditation only. It works like ExprSetProperty() during VVA
-** processes but is a no-op for delivery.
-*/
-#ifdef SQLITE_DEBUG
-# define ExprSetVVAProperty(E,P) (E)->flags|=(P)
-#else
-# define ExprSetVVAProperty(E,P)
-#endif
-
-/*
-** Macros to determine the number of bytes required by a normal Expr
-** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
-** and an Expr struct with the EP_TokenOnly flag set.
-*/
-#define EXPR_FULLSIZE sizeof(Expr) /* Full size */
-#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
-#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
-
-/*
-** Flags passed to the sqlite3ExprDup() function. See the header comment
-** above sqlite3ExprDup() for details.
-*/
-#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
-
-/*
-** A list of expressions. Each expression may optionally have a
-** name. An expr/name combination can be used in several ways, such
-** as the list of "expr AS ID" fields following a "SELECT" or in the
-** list of "ID = expr" items in an UPDATE. A list of expressions can
-** also be used as the argument to a function, in which case the a.zName
-** field is not used.
-**
-** By default the Expr.zSpan field holds a human-readable description of
-** the expression that is used in the generation of error messages and
-** column labels. In this case, Expr.zSpan is typically the text of a
-** column expression as it exists in a SELECT statement. However, if
-** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
-** of the result column in the form: DATABASE.TABLE.COLUMN. This later
-** form is used for name resolution with nested FROM clauses.
-*/
-struct ExprList {
- int nExpr; /* Number of expressions on the list */
- struct ExprList_item { /* For each expression in the list */
- Expr *pExpr; /* The parse tree for this expression */
- char *zName; /* Token associated with this expression */
- char *zSpan; /* Original text of the expression */
- u8 sortOrder; /* 1 for DESC or 0 for ASC */
- unsigned done :1; /* A flag to indicate when processing is finished */
- unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
- unsigned reusable :1; /* Constant expression is reusable */
- unsigned bSorterRef :1; /* Defer evaluation until after sorting */
- union {
- struct {
- u16 iOrderByCol; /* For ORDER BY, column number in result set */
- u16 iAlias; /* Index into Parse.aAlias[] for zName */
- } x;
- int iConstExprReg; /* Register in which Expr value is cached */
- } u;
- } a[1]; /* One slot for each expression in the list */
-};
-
-/*
-** An instance of this structure can hold a simple list of identifiers,
-** such as the list "a,b,c" in the following statements:
-**
-** INSERT INTO t(a,b,c) VALUES ...;
-** CREATE INDEX idx ON t(a,b,c);
-** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
-**
-** The IdList.a.idx field is used when the IdList represents the list of
-** column names after a table name in an INSERT statement. In the statement
-**
-** INSERT INTO t(a,b,c) ...
-**
-** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
-*/
-struct IdList {
- struct IdList_item {
- char *zName; /* Name of the identifier */
- int idx; /* Index in some Table.aCol[] of a column named zName */
- } *a;
- int nId; /* Number of identifiers on the list */
-};
-
-/*
-** The following structure describes the FROM clause of a SELECT statement.
-** Each table or subquery in the FROM clause is a separate element of
-** the SrcList.a[] array.
-**
-** With the addition of multiple database support, the following structure
-** can also be used to describe a particular table such as the table that
-** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
-** such a table must be a simple name: ID. But in SQLite, the table can
-** now be identified by a database name, a dot, then the table name: ID.ID.
-**
-** The jointype starts out showing the join type between the current table
-** and the next table on the list. The parser builds the list this way.
-** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
-** jointype expresses the join between the table and the previous table.
-**
-** In the colUsed field, the high-order bit (bit 63) is set if the table
-** contains more than 63 columns and the 64-th or later column is used.
-*/
-struct SrcList {
- int nSrc; /* Number of tables or subqueries in the FROM clause */
- u32 nAlloc; /* Number of entries allocated in a[] below */
- struct SrcList_item {
- Schema *pSchema; /* Schema to which this item is fixed */
- char *zDatabase; /* Name of database holding this table */
- char *zName; /* Name of the table */
- char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
- Table *pTab; /* An SQL table corresponding to zName */
- Select *pSelect; /* A SELECT statement used in place of a table name */
- int addrFillSub; /* Address of subroutine to manifest a subquery */
- int regReturn; /* Register holding return address of addrFillSub */
- int regResult; /* Registers holding results of a co-routine */
- struct {
- u8 jointype; /* Type of join between this table and the previous */
- unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
- unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
- unsigned isTabFunc :1; /* True if table-valued-function syntax */
- unsigned isCorrelated :1; /* True if sub-query is correlated */
- unsigned viaCoroutine :1; /* Implemented as a co-routine */
- unsigned isRecursive :1; /* True for recursive reference in WITH */
- } fg;
- int iCursor; /* The VDBE cursor number used to access this table */
- Expr *pOn; /* The ON clause of a join */
- IdList *pUsing; /* The USING clause of a join */
- Bitmask colUsed; /* Bit N (1<" clause */
- ExprList *pFuncArg; /* Arguments to table-valued-function */
- } u1;
- Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
- } a[1]; /* One entry for each identifier on the list */
-};
-
-/*
-** Permitted values of the SrcList.a.jointype field
-*/
-#define JT_INNER 0x0001 /* Any kind of inner or cross join */
-#define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
-#define JT_NATURAL 0x0004 /* True for a "natural" join */
-#define JT_LEFT 0x0008 /* Left outer join */
-#define JT_RIGHT 0x0010 /* Right outer join */
-#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
-#define JT_ERROR 0x0040 /* unknown or unsupported join type */
-
-
-/*
-** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
-** and the WhereInfo.wctrlFlags member.
-**
-** Value constraints (enforced via assert()):
-** WHERE_USE_LIMIT == SF_FixedLimit
-*/
-#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
-#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
-#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
-#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
-#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
-#define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
-#define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
- ** the OR optimization */
-#define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
-#define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
-#define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
-#define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
-#define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
-#define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
-#define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
- /* 0x2000 not currently used */
-#define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
- /* 0x8000 not currently used */
-
-/* Allowed return values from sqlite3WhereIsDistinct()
-*/
-#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
-#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
-#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
-#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
-
-/*
-** A NameContext defines a context in which to resolve table and column
-** names. The context consists of a list of tables (the pSrcList) field and
-** a list of named expression (pEList). The named expression list may
-** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
-** to the table being operated on by INSERT, UPDATE, or DELETE. The
-** pEList corresponds to the result set of a SELECT and is NULL for
-** other statements.
-**
-** NameContexts can be nested. When resolving names, the inner-most
-** context is searched first. If no match is found, the next outer
-** context is checked. If there is still no match, the next context
-** is checked. This process continues until either a match is found
-** or all contexts are check. When a match is found, the nRef member of
-** the context containing the match is incremented.
-**
-** Each subquery gets a new NameContext. The pNext field points to the
-** NameContext in the parent query. Thus the process of scanning the
-** NameContext list corresponds to searching through successively outer
-** subqueries looking for a match.
-*/
-struct NameContext {
- Parse *pParse; /* The parser */
- SrcList *pSrcList; /* One or more tables used to resolve names */
- union {
- ExprList *pEList; /* Optional list of result-set columns */
- AggInfo *pAggInfo; /* Information about aggregates at this level */
- Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
- } uNC;
- NameContext *pNext; /* Next outer name context. NULL for outermost */
- int nRef; /* Number of names resolved by this context */
- int nErr; /* Number of errors encountered while resolving names */
- int ncFlags; /* Zero or more NC_* flags defined below */
- Select *pWinSelect; /* SELECT statement for any window functions */
-};
-
-/*
-** Allowed values for the NameContext, ncFlags field.
-**
-** Value constraints (all checked via assert()):
-** NC_HasAgg == SF_HasAgg == EP_Agg
-** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
-** NC_HasWin == EP_Win
-**
-*/
-#define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
-#define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
-#define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
-#define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
-#define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
-#define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
-#define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
-#define NC_UEList 0x0080 /* True if uNC.pEList is used */
-#define NC_UAggInfo 0x0100 /* True if uNC.pAggInfo is used */
-#define NC_UUpsert 0x0200 /* True if uNC.pUpsert is used */
-#define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
-#define NC_Complex 0x2000 /* True if a function or subquery seen */
-#define NC_AllowWin 0x4000 /* Window functions are allowed here */
-#define NC_HasWin 0x8000 /* One or more window functions seen */
-#define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */
-
-/*
-** An instance of the following object describes a single ON CONFLICT
-** clause in an upsert.
-**
-** The pUpsertTarget field is only set if the ON CONFLICT clause includes
-** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
-** conflict-target clause.) The pUpsertTargetWhere is the optional
-** WHERE clause used to identify partial unique indexes.
-**
-** pUpsertSet is the list of column=expr terms of the UPDATE statement.
-** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
-** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
-** WHERE clause is omitted.
-*/
-struct Upsert {
- ExprList *pUpsertTarget; /* Optional description of conflicting index */
- Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
- ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
- Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
- /* The fields above comprise the parse tree for the upsert clause.
- ** The fields below are used to transfer information from the INSERT
- ** processing down into the UPDATE processing while generating code.
- ** Upsert owns the memory allocated above, but not the memory below. */
- Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
- SrcList *pUpsertSrc; /* Table to be updated */
- int regData; /* First register holding array of VALUES */
- int iDataCur; /* Index of the data cursor */
- int iIdxCur; /* Index of the first index cursor */
-};
-
-/*
-** An instance of the following structure contains all information
-** needed to generate code for a single SELECT statement.
-**
-** See the header comment on the computeLimitRegisters() routine for a
-** detailed description of the meaning of the iLimit and iOffset fields.
-**
-** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
-** These addresses must be stored so that we can go back and fill in
-** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
-** the number of columns in P2 can be computed at the same time
-** as the OP_OpenEphm instruction is coded because not
-** enough information about the compound query is known at that point.
-** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
-** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
-** sequences for the ORDER BY clause.
-*/
-struct Select {
- ExprList *pEList; /* The fields of the result */
- u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
- LogEst nSelectRow; /* Estimated number of result rows */
- u32 selFlags; /* Various SF_* values */
- int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
- u32 selId; /* Unique identifier number for this SELECT */
- int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
- SrcList *pSrc; /* The FROM clause */
- Expr *pWhere; /* The WHERE clause */
- ExprList *pGroupBy; /* The GROUP BY clause */
- Expr *pHaving; /* The HAVING clause */
- ExprList *pOrderBy; /* The ORDER BY clause */
- Select *pPrior; /* Prior select in a compound select statement */
- Select *pNext; /* Next select to the left in a compound */
- Expr *pLimit; /* LIMIT expression. NULL means not used. */
- With *pWith; /* WITH clause attached to this select. Or NULL. */
-#ifndef SQLITE_OMIT_WINDOWFUNC
- Window *pWin; /* List of window functions */
- Window *pWinDefn; /* List of named window definitions */
-#endif
-};
-
-/*
-** Allowed values for Select.selFlags. The "SF" prefix stands for
-** "Select Flag".
-**
-** Value constraints (all checked via assert())
-** SF_HasAgg == NC_HasAgg
-** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
-** SF_FixedLimit == WHERE_USE_LIMIT
-*/
-#define SF_Distinct 0x00001 /* Output should be DISTINCT */
-#define SF_All 0x00002 /* Includes the ALL keyword */
-#define SF_Resolved 0x00004 /* Identifiers have been resolved */
-#define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
-#define SF_HasAgg 0x00010 /* Contains aggregate functions */
-#define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
-#define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
-#define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
-#define SF_Compound 0x00100 /* Part of a compound query */
-#define SF_Values 0x00200 /* Synthesized from VALUES clause */
-#define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
-#define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
-#define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
-#define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
-#define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
-#define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
-#define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
-#define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
-#define SF_ComplexResult 0x40000 /* Result contains subquery or function */
-
-/*
-** The results of a SELECT can be distributed in several ways, as defined
-** by one of the following macros. The "SRT" prefix means "SELECT Result
-** Type".
-**
-** SRT_Union Store results as a key in a temporary index
-** identified by pDest->iSDParm.
-**
-** SRT_Except Remove results from the temporary index pDest->iSDParm.
-**
-** SRT_Exists Store a 1 in memory cell pDest->iSDParm 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.
-**
-** All of the above are free to ignore their ORDER BY clause. Those that
-** follow must honor the ORDER BY clause.
-**
-** 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->iSDParm 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->iSDParm.
-** Apply the affinity pDest->affSdst before storing
-** results. Used to implement "IN (SELECT ...)".
-**
-** SRT_EphemTab Create an temporary table pDest->iSDParm 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->iSDParm
-** and the result row is stored in pDest->nDest registers
-** starting with pDest->iSdst.
-**
-** SRT_Table Store results in temporary table pDest->iSDParm.
-** SRT_Fifo This is like SRT_EphemTab except that the table
-** is assumed to already be open. SRT_Fifo has
-** the additional property of being able to ignore
-** the ORDER BY clause.
-**
-** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
-** But also use temporary table pDest->iSDParm+1 as
-** a record of all prior results and ignore any duplicate
-** rows. Name means: "Distinct Fifo".
-**
-** SRT_Queue Store results in priority queue pDest->iSDParm (really
-** an index). Append a sequence number so that all entries
-** are distinct.
-**
-** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
-** the same record has never been stored before. The
-** index at pDest->iSDParm+1 hold all prior stores.
-*/
-#define SRT_Union 1 /* Store result as keys in an index */
-#define SRT_Except 2 /* Remove result from a UNION index */
-#define SRT_Exists 3 /* Store 1 if the result is not empty */
-#define SRT_Discard 4 /* Do not save the results anywhere */
-#define SRT_Fifo 5 /* Store result as data with an automatic rowid */
-#define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
-#define SRT_Queue 7 /* Store result in an queue */
-#define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
-
-/* The ORDER BY clause is ignored for all of the above */
-#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
-
-#define SRT_Output 9 /* Output each row of result */
-#define SRT_Mem 10 /* Store result in a memory cell */
-#define SRT_Set 11 /* Store results as keys in an index */
-#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
-#define SRT_Coroutine 13 /* Generate a single row of result */
-#define SRT_Table 14 /* Store result as data with an automatic rowid */
-
-/*
-** An instance of this object describes where to put of the results of
-** a SELECT statement.
-*/
-struct SelectDest {
- u8 eDest; /* How to dispose of the results. On of SRT_* above. */
- int iSDParm; /* A parameter used by the eDest disposal method */
- int iSdst; /* Base register where results are written */
- int nSdst; /* Number of registers allocated */
- char *zAffSdst; /* Affinity used when eDest==SRT_Set */
- ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
-};
-
-/*
-** During code generation of statements that do inserts into AUTOINCREMENT
-** tables, the following information is attached to the Table.u.autoInc.p
-** pointer of each autoincrement table to record some side information that
-** the code generator needs. We have to keep per-table autoincrement
-** information in case inserts are done within triggers. Triggers do not
-** normally coordinate their activities, but we do need to coordinate the
-** loading and saving of autoincrement information.
-*/
-struct AutoincInfo {
- AutoincInfo *pNext; /* Next info block in a list of them all */
- Table *pTab; /* Table this info block refers to */
- int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
- int regCtr; /* Memory register holding the rowid counter */
-};
-
-/*
-** At least one instance of the following structure is created for each
-** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
-** statement. All such objects are stored in the linked list headed at
-** Parse.pTriggerPrg and deleted once statement compilation has been
-** completed.
-**
-** A Vdbe sub-program that implements the body and WHEN clause of trigger
-** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
-** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
-** The Parse.pTriggerPrg list never contains two entries with the same
-** values for both pTrigger and orconf.
-**
-** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
-** accessed (or set to 0 for triggers fired as a result of INSERT
-** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
-** a mask of new.* columns used by the program.
-*/
-struct TriggerPrg {
- Trigger *pTrigger; /* Trigger this program was coded from */
- TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
- SubProgram *pProgram; /* Program implementing pTrigger/orconf */
- int orconf; /* Default ON CONFLICT policy */
- u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
-};
-
-/*
-** The yDbMask datatype for the bitmask of all attached databases.
-*/
-#if SQLITE_MAX_ATTACHED>30
- typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
-# define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
-# define DbMaskZero(M) memset((M),0,sizeof(M))
-# define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
-# define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
-# define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
-#else
- typedef unsigned int yDbMask;
-# define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
-# define DbMaskZero(M) (M)=0
-# define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
-# define DbMaskAllZero(M) (M)==0
-# define DbMaskNonZero(M) (M)!=0
-#endif
-
-/*
-** An SQL parser context. A copy of this structure is passed through
-** the parser and down into all the parser action routine in order to
-** carry around information that is global to the entire parse.
-**
-** The structure is divided into two parts. When the parser and code
-** generate call themselves recursively, the first part of the structure
-** is constant but the second part is reset at the beginning and end of
-** each recursion.
-**
-** The nTableLock and aTableLock variables are only used if the shared-cache
-** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
-** used to store the set of table-locks required by the statement being
-** compiled. Function sqlite3TableLock() is used to add entries to the
-** list.
-*/
-struct Parse {
- sqlite3 *db; /* The main database structure */
- char *zErrMsg; /* An error message */
- Vdbe *pVdbe; /* An engine for executing database bytecode */
- int rc; /* Return code from execution */
- u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
- u8 checkSchema; /* Causes schema cookie check after an error */
- u8 nested; /* Number of nested calls to the parser/code generator */
- u8 nTempReg; /* Number of temporary registers in aTempReg[] */
- u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
- u8 mayAbort; /* True if statement may throw an ABORT exception */
- u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
- u8 okConstFactor; /* OK to factor out constants */
- u8 disableLookaside; /* Number of times lookaside has been disabled */
- u8 disableVtab; /* Disable all virtual tables for this parse */
- int nRangeReg; /* Size of the temporary register block */
- int iRangeReg; /* First register in temporary register block */
- int nErr; /* Number of errors seen */
- int nTab; /* Number of previously allocated VDBE cursors */
- int nMem; /* Number of memory cells used so far */
- int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
- int iSelfTab; /* Table associated with an index on expr, or negative
- ** of the base register during check-constraint eval */
- int nLabel; /* The *negative* of the number of labels used */
- int nLabelAlloc; /* Number of slots in aLabel */
- int *aLabel; /* Space to hold the labels */
- ExprList *pConstExpr;/* Constant expressions */
- Token constraintName;/* Name of the constraint currently being parsed */
- yDbMask writeMask; /* Start a write transaction on these databases */
- yDbMask cookieMask; /* Bitmask of schema verified databases */
- int regRowid; /* Register holding rowid of CREATE TABLE entry */
- int regRoot; /* Register holding root page number for new objects */
- int nMaxArg; /* Max args passed to user function by sub-program */
- int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
-#ifndef SQLITE_OMIT_SHARED_CACHE
- int nTableLock; /* Number of locks in aTableLock */
- TableLock *aTableLock; /* Required table locks for shared-cache mode */
-#endif
- AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
- Parse *pToplevel; /* Parse structure for main program (or NULL) */
- Table *pTriggerTab; /* Table triggers are being coded for */
- Parse *pParentParse; /* Parent parser if this parser is nested */
- int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
- u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
- u32 oldmask; /* Mask of old.* columns referenced */
- u32 newmask; /* Mask of new.* columns referenced */
- u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
- u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
- u8 disableTriggers; /* True to disable triggers */
-
- /**************************************************************************
- ** Fields above must be initialized to zero. The fields that follow,
- ** down to the beginning of the recursive section, do not need to be
- ** initialized as they will be set before being used. The boundary is
- ** determined by offsetof(Parse,aTempReg).
- **************************************************************************/
-
- int aTempReg[8]; /* Holding area for temporary registers */
- Token sNameToken; /* Token with unqualified schema object name */
-
- /************************************************************************
- ** Above is constant between recursions. Below is reset before and after
- ** each recursion. The boundary between these two regions is determined
- ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
- ** first field in the recursive region.
- ************************************************************************/
-
- Token sLastToken; /* The last token parsed */
- ynVar nVar; /* Number of '?' variables seen in the SQL so far */
- u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
- u8 explain; /* True if the EXPLAIN flag is found on the query */
-#if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
- u8 eParseMode; /* PARSE_MODE_XXX constant */
-#endif
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- int nVtabLock; /* Number of virtual tables to lock */
-#endif
- int nHeight; /* Expression tree height of current sub-select */
-#ifndef SQLITE_OMIT_EXPLAIN
- int addrExplain; /* Address of current OP_Explain opcode */
-#endif
- VList *pVList; /* Mapping between variable names and numbers */
- Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
- const char *zTail; /* All SQL text past the last semicolon parsed */
- Table *pNewTable; /* A table being constructed by CREATE TABLE */
- Index *pNewIndex; /* An index being constructed by CREATE INDEX.
- ** Also used to hold redundant UNIQUE constraints
- ** during a RENAME COLUMN */
- Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
- const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
-#ifndef SQLITE_OMIT_VIRTUALTABLE
- Token sArg; /* Complete text of a module argument */
- Table **apVtabLock; /* Pointer to virtual tables needing locking */
-#endif
- Table *pZombieTab; /* List of Table objects to delete after code gen */
- TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
- With *pWith; /* Current WITH clause, or NULL */
- With *pWithToFree; /* Free this WITH object at the end of the parse */
-#ifndef SQLITE_OMIT_ALTERTABLE
- RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
-#endif
-};
-
-#define PARSE_MODE_NORMAL 0
-#define PARSE_MODE_DECLARE_VTAB 1
-#define PARSE_MODE_RENAME_COLUMN 2
-#define PARSE_MODE_RENAME_TABLE 3
-
-/*
-** Sizes and pointers of various parts of the Parse object.
-*/
-#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
-#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
-#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
-#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
-
-/*
-** Return true if currently inside an sqlite3_declare_vtab() call.
-*/
-#ifdef SQLITE_OMIT_VIRTUALTABLE
- #define IN_DECLARE_VTAB 0
-#else
- #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
-#endif
-
-#if defined(SQLITE_OMIT_ALTERTABLE)
- #define IN_RENAME_OBJECT 0
-#else
- #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
-#endif
-
-#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
- #define IN_SPECIAL_PARSE 0
-#else
- #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
-#endif
-
-/*
-** An instance of the following structure can be declared on a stack and used
-** to save the Parse.zAuthContext value so that it can be restored later.
-*/
-struct AuthContext {
- const char *zAuthContext; /* Put saved Parse.zAuthContext here */
- Parse *pParse; /* The Parse structure */
-};
-
-/*
-** Bitfield flags for P5 value in various opcodes.
-**
-** Value constraints (enforced via assert()):
-** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
-** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
-** OPFLAG_BULKCSR == BTREE_BULKLOAD
-** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
-** OPFLAG_FORDELETE == BTREE_FORDELETE
-** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
-** OPFLAG_AUXDELETE == BTREE_AUXDELETE
-*/
-#define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
- /* Also used in P2 (not P5) of OP_Delete */
-#define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
-#define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
-#define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
-#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
-#define OPFLAG_APPEND 0x08 /* This is likely to be an append */
-#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
-#define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
-#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
-#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
-#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
-#define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
-#define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
-#define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
-#define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
-#define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
-#define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
-#define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
-
-/*
- * Each trigger present in the database schema is stored as an instance of
- * struct Trigger.
- *
- * Pointers to instances of struct Trigger are stored in two ways.
- * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
- * database). This allows Trigger structures to be retrieved by name.
- * 2. All triggers associated with a single table form a linked list, using the
- * pNext member of struct Trigger. A pointer to the first element of the
- * linked list is stored as the "pTrigger" member of the associated
- * struct Table.
- *
- * The "step_list" member points to the first element of a linked list
- * containing the SQL statements specified as the trigger program.
- */
-struct Trigger {
- char *zName; /* The name of the trigger */
- char *table; /* The table or view to which the trigger applies */
- u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
- u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
- Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
- IdList *pColumns; /* If this is an UPDATE OF trigger,
- the is stored here */
- Schema *pSchema; /* Schema containing the trigger */
- Schema *pTabSchema; /* Schema containing the table */
- TriggerStep *step_list; /* Link list of trigger program steps */
- Trigger *pNext; /* Next trigger associated with the table */
-};
-
-/*
-** A trigger is either a BEFORE or an AFTER trigger. The following constants
-** determine which.
-**
-** If there are multiple triggers, you might of some BEFORE and some AFTER.
-** In that cases, the constants below can be ORed together.
-*/
-#define TRIGGER_BEFORE 1
-#define TRIGGER_AFTER 2
-
-/*
- * An instance of struct TriggerStep is used to store a single SQL statement
- * that is a part of a trigger-program.
- *
- * Instances of struct TriggerStep are stored in a singly linked list (linked
- * using the "pNext" member) referenced by the "step_list" member of the
- * associated struct Trigger instance. The first element of the linked list is
- * the first step of the trigger-program.
- *
- * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
- * "SELECT" statement. The meanings of the other members is determined by the
- * value of "op" as follows:
- *
- * (op == TK_INSERT)
- * orconf -> stores the ON CONFLICT algorithm
- * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
- * this stores a pointer to the SELECT statement. Otherwise NULL.
- * zTarget -> Dequoted name of the table to insert into.
- * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
- * this stores values to be inserted. Otherwise NULL.
- * pIdList -> If this is an INSERT INTO ... () VALUES ...
- * statement, then this stores the column-names to be
- * inserted into.
- *
- * (op == TK_DELETE)
- * zTarget -> Dequoted name of the table to delete from.
- * pWhere -> The WHERE clause of the DELETE statement if one is specified.
- * Otherwise NULL.
- *
- * (op == TK_UPDATE)
- * zTarget -> Dequoted name of the table to update.
- * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
- * Otherwise NULL.
- * pExprList -> A list of the columns to update and the expressions to update
- * them to. See sqlite3Update() documentation of "pChanges"
- * argument.
- *
- */
-struct TriggerStep {
- u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
- u8 orconf; /* OE_Rollback etc. */
- Trigger *pTrig; /* The trigger that this step is a part of */
- Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
- char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
- Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
- ExprList *pExprList; /* SET clause for UPDATE */
- IdList *pIdList; /* Column names for INSERT */
- Upsert *pUpsert; /* Upsert clauses on an INSERT */
- char *zSpan; /* Original SQL text of this command */
- TriggerStep *pNext; /* Next in the link-list */
- TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
-};
-
-/*
-** The following structure contains information used by the sqliteFix...
-** routines as they walk the parse tree to make database references
-** explicit.
-*/
-typedef struct DbFixer DbFixer;
-struct DbFixer {
- Parse *pParse; /* The parsing context. Error messages written here */
- Schema *pSchema; /* Fix items to this schema */
- int bVarOnly; /* Check for variable references only */
- const char *zDb; /* Make sure all objects are contained in this database */
- const char *zType; /* Type of the container - used for error messages */
- const Token *pName; /* Name of the container - used for error messages */
-};
-
-/*
-** An objected used to accumulate the text of a string where we
-** do not necessarily know how big the string will be in the end.
-*/
-struct sqlite3_str {
- sqlite3 *db; /* Optional database for lookaside. Can be NULL */
- char *zText; /* The string collected so far */
- u32 nAlloc; /* Amount of space allocated in zText */
- u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
- u32 nChar; /* Length of the string so far */
- u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
- u8 printfFlags; /* SQLITE_PRINTF flags below */
-};
-#define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
-#define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
-#define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
-
-#define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
-
-
-/*
-** A pointer to this structure is used to communicate information
-** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
-*/
-typedef struct {
- sqlite3 *db; /* The database being initialized */
- char **pzErrMsg; /* Error message stored here */
- int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
- int rc; /* Result code stored here */
- u32 mInitFlags; /* Flags controlling error messages */
- u32 nInitRow; /* Number of rows processed */
-} InitData;
-
-/*
-** Allowed values for mInitFlags
-*/
-#define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
-
-/*
-** Structure containing global configuration data for the SQLite library.
-**
-** This structure also contains some state information.
-*/
-struct Sqlite3Config {
- int bMemstat; /* True to enable memory status */
- int bCoreMutex; /* True to enable core mutexing */
- int bFullMutex; /* True to enable full mutexing */
- int bOpenUri; /* True to interpret filenames as URIs */
- int bUseCis; /* Use covering indices for full-scans */
- int bSmallMalloc; /* Avoid large memory allocations if true */
- int mxStrlen; /* Maximum string length */
- int neverCorrupt; /* Database is always well-formed */
- int szLookaside; /* Default lookaside buffer size */
- int nLookaside; /* Default lookaside buffer count */
- int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
- sqlite3_mem_methods m; /* Low-level memory allocation interface */
- sqlite3_mutex_methods mutex; /* Low-level mutex interface */
- sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
- void *pHeap; /* Heap storage space */
- int nHeap; /* Size of pHeap[] */
- int mnReq, mxReq; /* Min and max heap requests sizes */
- sqlite3_int64 szMmap; /* mmap() space per open file */
- sqlite3_int64 mxMmap; /* Maximum value for szMmap */
- void *pPage; /* Page cache memory */
- int szPage; /* Size of each page in pPage[] */
- int nPage; /* Number of pages in pPage[] */
- int mxParserStack; /* maximum depth of the parser stack */
- int sharedCacheEnabled; /* true if shared-cache mode enabled */
- u32 szPma; /* Maximum Sorter PMA size */
- /* The above might be initialized to non-zero. The following need to always
- ** initially be zero, however. */
- int isInit; /* True after initialization has finished */
- int inProgress; /* True while initialization in progress */
- int isMutexInit; /* True after mutexes are initialized */
- int isMallocInit; /* True after malloc is initialized */
- int isPCacheInit; /* True after malloc is initialized */
- int nRefInitMutex; /* Number of users of pInitMutex */
- sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
- void (*xLog)(void*,int,const char*); /* Function for logging */
- void *pLogArg; /* First argument to xLog() */
-#ifdef SQLITE_ENABLE_SQLLOG
- void(*xSqllog)(void*,sqlite3*,const char*, int);
- void *pSqllogArg;
-#endif
-#ifdef SQLITE_VDBE_COVERAGE
- /* The following callback (if not NULL) is invoked on every VDBE branch
- ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
- */
- void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
- void *pVdbeBranchArg; /* 1st argument */
-#endif
-#ifdef SQLITE_ENABLE_DESERIALIZE
- sqlite3_int64 mxMemdbSize; /* Default max memdb size */
-#endif
-#ifndef SQLITE_UNTESTABLE
- int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
-#endif
- int bLocaltimeFault; /* True to fail localtime() calls */
- int bInternalFunctions; /* Internal SQL functions are visible */
- int iOnceResetThreshold; /* When to reset OP_Once counters */
- u32 szSorterRef; /* Min size in bytes to use sorter-refs */
-};
-
-/*
-** This macro is used inside of assert() statements to indicate that
-** the assert is only valid on a well-formed database. Instead of:
-**
-** assert( X );
-**
-** One writes:
-**
-** assert( X || CORRUPT_DB );
-**
-** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
-** that the database is definitely corrupt, only that it might be corrupt.
-** For most test cases, CORRUPT_DB is set to false using a special
-** sqlite3_test_control(). This enables assert() statements to prove
-** things that are always true for well-formed databases.
-*/
-#define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
-
-/*
-** Context pointer passed down through the tree-walk.
-*/
-struct Walker {
- Parse *pParse; /* Parser context. */
- int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
- int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
- void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
- int walkerDepth; /* Number of subqueries */
- u8 eCode; /* A small processing code */
- union { /* Extra data for callback */
- NameContext *pNC; /* Naming context */
- int n; /* A counter */
- int iCur; /* A cursor number */
- SrcList *pSrcList; /* FROM clause */
- struct SrcCount *pSrcCount; /* Counting column references */
- struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
- int *aiCol; /* array of column indexes */
- struct IdxCover *pIdxCover; /* Check for index coverage */
- struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
- ExprList *pGroupBy; /* GROUP BY clause */
- Select *pSelect; /* HAVING to WHERE clause ctx */
- struct WindowRewrite *pRewrite; /* Window rewrite context */
- struct WhereConst *pConst; /* WHERE clause constants */
- struct RenameCtx *pRename; /* RENAME COLUMN context */
- } u;
-};
-
-/* Forward declarations */
-SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
-SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
-SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
-SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
-SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
-SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
-SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
-SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
-#endif
-
-/*
-** Return code from the parse-tree walking primitives and their
-** callbacks.
-*/
-#define WRC_Continue 0 /* Continue down into children */
-#define WRC_Prune 1 /* Omit children but continue walking siblings */
-#define WRC_Abort 2 /* Abandon the tree walk */
-
-/*
-** An instance of this structure represents a set of one or more CTEs
-** (common table expressions) created by a single WITH clause.
-*/
-struct With {
- int nCte; /* Number of CTEs in the WITH clause */
- With *pOuter; /* Containing WITH clause, or NULL */
- struct Cte { /* For each CTE in the WITH clause.... */
- char *zName; /* Name of this CTE */
- ExprList *pCols; /* List of explicit column names, or NULL */
- Select *pSelect; /* The definition of this CTE */
- const char *zCteErr; /* Error message for circular references */
- } a[1];
-};
-
-#ifdef SQLITE_DEBUG
-/*
-** An instance of the TreeView object is used for printing the content of
-** data structures on sqlite3DebugPrintf() using a tree-like view.
-*/
-struct TreeView {
- int iLevel; /* Which level of the tree we are on */
- u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
-};
-#endif /* SQLITE_DEBUG */
-
-/*
-** This object is used in various ways, all related to window functions
-**
-** (1) A single instance of this structure is attached to the
-** the Expr.pWin field for each window function in an expression tree.
-** This object holds the information contained in the OVER clause,
-** plus additional fields used during code generation.
-**
-** (2) All window functions in a single SELECT form a linked-list
-** attached to Select.pWin. The Window.pFunc and Window.pExpr
-** fields point back to the expression that is the window function.
-**
-** (3) The terms of the WINDOW clause of a SELECT are instances of this
-** object on a linked list attached to Select.pWinDefn.
-**
-** The uses (1) and (2) are really the same Window object that just happens
-** to be accessible in two different ways. Use case (3) are separate objects.
-*/
-struct Window {
- char *zName; /* Name of window (may be NULL) */
- char *zBase; /* Name of base window for chaining (may be NULL) */
- ExprList *pPartition; /* PARTITION BY clause */
- ExprList *pOrderBy; /* ORDER BY clause */
- u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
- u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
- u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
- u8 bImplicitFrame; /* True if frame was implicitly specified */
- u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
- Expr *pStart; /* Expression for " PRECEDING" */
- Expr *pEnd; /* Expression for " FOLLOWING" */
- Window *pNextWin; /* Next window function belonging to this SELECT */
- Expr *pFilter; /* The FILTER expression */
- FuncDef *pFunc; /* The function */
- int iEphCsr; /* Partition buffer or Peer buffer */
- int regAccum;
- int regResult;
- int csrApp; /* Function cursor (used by min/max) */
- int regApp; /* Function register (also used by min/max) */
- int regPart; /* Array of registers for PARTITION BY values */
- Expr *pOwner; /* Expression object this window is attached to */
- int nBufferCol; /* Number of columns in buffer table */
- int iArgCol; /* Offset of first argument for this function */
- int regOne; /* Register containing constant value 1 */
- int regStartRowid;
- int regEndRowid;
-};
-
-#ifndef SQLITE_OMIT_WINDOWFUNC
-SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
-SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
-SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
-SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
-SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*);
-SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
-SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
-SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
-SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
-SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
-SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
-SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
-SQLITE_PRIVATE void sqlite3WindowFunctions(void);
-SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
-SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
-#else
-# define sqlite3WindowDelete(a,b)
-# define sqlite3WindowFunctions()
-# define sqlite3WindowAttach(a,b,c)
-#endif
-
-/*
-** Assuming zIn points to the first byte of a UTF-8 character,
-** advance zIn to point to the first byte of the next UTF-8 character.
-*/
-#define SQLITE_SKIP_UTF8(zIn) { \
- if( (*(zIn++))>=0xc0 ){ \
- while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
- } \
-}
-
-/*
-** The SQLITE_*_BKPT macros are substitutes for the error codes with
-** the same name but without the _BKPT suffix. These macros invoke
-** routines that report the line-number on which the error originated
-** using sqlite3_log(). The routines also provide a convenient place
-** to set a debugger breakpoint.
-*/
-SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
-SQLITE_PRIVATE int sqlite3CorruptError(int);
-SQLITE_PRIVATE int sqlite3MisuseError(int);
-SQLITE_PRIVATE int sqlite3CantopenError(int);
-#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
-#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
-#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3NomemError(int);
-SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
-SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
-# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
-# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
-# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
-#else
-# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
-# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
-# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
-#endif
-
-/*
-** FTS3 and FTS4 both require virtual table support
-*/
-#if defined(SQLITE_OMIT_VIRTUALTABLE)
-# undef SQLITE_ENABLE_FTS3
-# undef SQLITE_ENABLE_FTS4
-#endif
-
-/*
-** FTS4 is really an extension for FTS3. It is enabled using the
-** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
-** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
-*/
-#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
-# define SQLITE_ENABLE_FTS3 1
-#endif
-
-/*
-** The ctype.h header is needed for non-ASCII systems. It is also
-** needed by FTS3 when FTS3 is included in the amalgamation.
-*/
-#if !defined(SQLITE_ASCII) || \
- (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
-# include
-#endif
-
-/*
-** The following macros mimic the standard library functions toupper(),
-** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
-** sqlite versions only work for ASCII characters, regardless of locale.
-*/
-#ifdef SQLITE_ASCII
-# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
-# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
-# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
-# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
-# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
-# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
-# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
-# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
-#else
-# define sqlite3Toupper(x) toupper((unsigned char)(x))
-# define sqlite3Isspace(x) isspace((unsigned char)(x))
-# define sqlite3Isalnum(x) isalnum((unsigned char)(x))
-# define sqlite3Isalpha(x) isalpha((unsigned char)(x))
-# define sqlite3Isdigit(x) isdigit((unsigned char)(x))
-# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
-# define sqlite3Tolower(x) tolower((unsigned char)(x))
-# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
-#endif
-SQLITE_PRIVATE int sqlite3IsIdChar(u8);
-
-/*
-** Internal function prototypes
-*/
-SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
-SQLITE_PRIVATE int sqlite3Strlen30(const char*);
-#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
-SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
-#define sqlite3StrNICmp sqlite3_strnicmp
-
-SQLITE_PRIVATE int sqlite3MallocInit(void);
-SQLITE_PRIVATE void sqlite3MallocEnd(void);
-SQLITE_PRIVATE void *sqlite3Malloc(u64);
-SQLITE_PRIVATE void *sqlite3MallocZero(u64);
-SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
-SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
-SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
-SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
-SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
-SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
-SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
-SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
-SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
-SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
-SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
-SQLITE_PRIVATE int sqlite3MallocSize(void*);
-SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
-SQLITE_PRIVATE void *sqlite3PageMalloc(int);
-SQLITE_PRIVATE void sqlite3PageFree(void*);
-SQLITE_PRIVATE void sqlite3MemSetDefault(void);
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
-#endif
-SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
-
-/*
-** On systems with ample stack space and that support alloca(), make
-** use of alloca() to obtain space for large automatic objects. By default,
-** obtain space from malloc().
-**
-** The alloca() routine never returns NULL. This will cause code paths
-** that deal with sqlite3StackAlloc() failures to be unreachable.
-*/
-#ifdef SQLITE_USE_ALLOCA
-# define sqlite3StackAllocRaw(D,N) alloca(N)
-# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
-# define sqlite3StackFree(D,P)
-#else
-# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
-# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
-# define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
-#endif
-
-/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
-** are, disable MEMSYS3
-*/
-#ifdef SQLITE_ENABLE_MEMSYS5
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
-#undef SQLITE_ENABLE_MEMSYS3
-#endif
-#ifdef SQLITE_ENABLE_MEMSYS3
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
-#endif
-
-
-#ifndef SQLITE_MUTEX_OMIT
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
-SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
-SQLITE_PRIVATE int sqlite3MutexInit(void);
-SQLITE_PRIVATE int sqlite3MutexEnd(void);
-#endif
-#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
-SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
-#else
-# define sqlite3MemoryBarrier()
-#endif
-
-SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
-SQLITE_PRIVATE void sqlite3StatusUp(int, int);
-SQLITE_PRIVATE void sqlite3StatusDown(int, int);
-SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
-SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
-
-/* Access to mutexes used by sqlite3_status() */
-SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
-SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
-
-#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
-SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
-#else
-# define sqlite3MutexWarnOnContention(x)
-#endif
-
-#ifndef SQLITE_OMIT_FLOATING_POINT
-# define EXP754 (((u64)0x7ff)<<52)
-# define MAN754 ((((u64)1)<<52)-1)
-# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
-SQLITE_PRIVATE int sqlite3IsNaN(double);
-#else
-# define IsNaN(X) 0
-# define sqlite3IsNaN(X) 0
-#endif
-
-/*
-** An instance of the following structure holds information about SQL
-** functions arguments that are the parameters to the printf() function.
-*/
-struct PrintfArguments {
- int nArg; /* Total number of arguments */
- int nUsed; /* Number of arguments used so far */
- sqlite3_value **apArg; /* The argument values */
-};
-
-SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
-SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
-#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
-SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
-#endif
-#if defined(SQLITE_TEST)
-SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
-#endif
-
-#if defined(SQLITE_DEBUG)
-SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
-SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
-SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
-SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
-SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
-SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
-#ifndef SQLITE_OMIT_WINDOWFUNC
-SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
-SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
-#endif
-#endif
-
-
-SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
-SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
-SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
-SQLITE_PRIVATE void sqlite3Dequote(char*);
-SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
-SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
-SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
-SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
-SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
-SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
-SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
-SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
-SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
-SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
-#endif
-SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
-SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
-SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
-SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
-SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
-SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
-SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
-SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
-SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
-SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
-SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
-SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
-SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
-SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
-SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
-SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
-SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
-SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
-SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
-SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
-SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
-SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
-SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
-#endif
-SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
-SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
-SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
-SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
-SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
-SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
-SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
-SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
-SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
-SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
-SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
-SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
-#if SQLITE_ENABLE_HIDDEN_COLUMNS
-SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
-#else
-# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
-#endif
-SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
-SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
-SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
-SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
-SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
-SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
-SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
-SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
- sqlite3_vfs**,char**,char **);
-#ifdef SQLITE_HAS_CODEC
-SQLITE_PRIVATE int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
-#else
-# define sqlite3CodecQueryParameters(A,B,C) 0
-#endif
-SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
-
-#ifdef SQLITE_UNTESTABLE
-# define sqlite3FaultSim(X) SQLITE_OK
-#else
-SQLITE_PRIVATE int sqlite3FaultSim(int);
-#endif
-
-SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
-SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
-SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
-SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
-SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
-SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
-SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
-#endif
-
-SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
-SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
-SQLITE_PRIVATE void sqlite3RowSetClear(void*);
-SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
-SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
-SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
-
-SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
-
-#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
-SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
-#else
-# define sqlite3ViewGetColumnNames(A,B) 0
-#endif
-
-#if SQLITE_MAX_ATTACHED>30
-SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
-#endif
-SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
-SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
-SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
-SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
-#ifndef SQLITE_OMIT_AUTOINCREMENT
-SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
-SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
-#else
-# define sqlite3AutoincrementBegin(X)
-# define sqlite3AutoincrementEnd(X)
-#endif
-SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
-SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
-SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
-SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
-SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
-SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
-SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
- Token*, Select*, Expr*, IdList*);
-SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
-SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
-SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
-SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
-SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
-SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
-SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
-SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
-SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
- Expr*, int, int, u8);
-SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
-SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
-SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
- Expr*,ExprList*,u32,Expr*);
-SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
-SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
-SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
-SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
-#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
-SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
-#endif
-SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
-SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
- Upsert*);
-SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
-SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
-SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
-SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
-#define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
-#define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
-#define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
-SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
-SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
-SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
-SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
-SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
-SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
-SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
-SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
-SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
-#define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
-#define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
-#define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
-#define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
-SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
-SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
-SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
-SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
-#define LOCATE_VIEW 0x01
-#define LOCATE_NOERR 0x02
-SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
-SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
-SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
-SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
-SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
-SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
-SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
-SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
-SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
-SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
-SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
-SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
-SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
-SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
-SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE void sqlite3PrngSaveState(void);
-SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
-#endif
-SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
-SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
-SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
-SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
-SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
-SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
-SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
-SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
-SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
-SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
-SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
-SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
-SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
-SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
-SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
-#ifdef SQLITE_ENABLE_CURSOR_HINTS
-SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
-#endif
-SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
-SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
-SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
-SQLITE_PRIVATE int sqlite3IsRowid(const char*);
-SQLITE_PRIVATE void sqlite3GenerateRowDelete(
- Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
-SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
-SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
-SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
-SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
-SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
- u8,u8,int,int*,int*,Upsert*);
-#ifdef SQLITE_ENABLE_NULL_TRIM
-SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
-#else
-# define sqlite3SetMakeRecordP5(A,B)
-#endif
-SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
-SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
-SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
-SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
-SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
-SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
-SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
-SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
-SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
-SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
-SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
-SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
-SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
-SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
-SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
-SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
-SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
-SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
-SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
-SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
-SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
-SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
-
-#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
-SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
-#endif
-
-#ifndef SQLITE_OMIT_TRIGGER
-SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
- Expr*,int, int);
-SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
-SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
-SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
-SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
-SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
-SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
- int, int, int);
-SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
- void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
-SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
-SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
- const char*,const char*);
-SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
- Select*,u8,Upsert*,
- const char*,const char*);
-SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
- const char*,const char*);
-SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
- const char*,const char*);
-SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
-SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
-SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
-# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
-# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
-#else
-# define sqlite3TriggersExist(B,C,D,E,F) 0
-# define sqlite3DeleteTrigger(A,B)
-# define sqlite3DropTriggerPtr(A,B)
-# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
-# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
-# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
-# define sqlite3TriggerList(X, Y) 0
-# define sqlite3ParseToplevel(p) p
-# define sqlite3IsToplevel(p) 1
-# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
-#endif
-
-SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
-SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
-SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
-#ifndef SQLITE_OMIT_AUTHORIZATION
-SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
-SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
-SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
-SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
-SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
-#else
-# define sqlite3AuthRead(a,b,c,d)
-# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
-# define sqlite3AuthContextPush(a,b,c)
-# define sqlite3AuthContextPop(a) ((void)(a))
-#endif
-SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
-SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
-SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
-SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
-SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
-SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
-SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
-SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
-SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
-SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
-SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
-SQLITE_PRIVATE int sqlite3Atoi(const char*);
-#ifndef SQLITE_OMIT_UTF16
-SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
-#endif
-SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
-SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
-SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
-SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
-#endif
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
- defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
- defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
-SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
-#endif
-SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
-SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
-SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
-
-/*
-** Routines to read and write variable-length integers. These used to
-** be defined locally, but now we use the varint routines in the util.c
-** file.
-*/
-SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
-SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
-SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
-SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
-
-/*
-** The common case is for a varint to be a single byte. They following
-** macros handle the common case without a procedure call, but then call
-** the procedure for larger varints.
-*/
-#define getVarint32(A,B) \
- (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
-#define putVarint32(A,B) \
- (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
- sqlite3PutVarint((A),(B)))
-#define getVarint sqlite3GetVarint
-#define putVarint sqlite3PutVarint
-
-
-SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
-SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
-SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
-SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
-SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
-SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
-SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
-SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
-SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
-SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
-SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
-SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
-SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
-SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
-
-#if defined(SQLITE_NEED_ERR_NAME)
-SQLITE_PRIVATE const char *sqlite3ErrName(int);
-#endif
-
-#ifdef SQLITE_ENABLE_DESERIALIZE
-SQLITE_PRIVATE int sqlite3MemdbInit(void);
-#endif
-
-SQLITE_PRIVATE const char *sqlite3ErrStr(int);
-SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
-SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
-SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
-SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
-SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
-SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
-SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
-SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
-SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
-SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
-SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
-SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
-SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
-SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
-SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
-SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
-SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
-SQLITE_PRIVATE int sqlite3AbsInt32(int);
-#ifdef SQLITE_ENABLE_8_3_NAMES
-SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
-#else
-# define sqlite3FileSuffix3(X,Y)
-#endif
-SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
-
-SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
-SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
-SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
- void(*)(void*));
-SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
-SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
-#endif
-SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
-#ifndef SQLITE_OMIT_UTF16
-SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
-#endif
-SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
-SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
-#ifndef SQLITE_AMALGAMATION
-SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
-SQLITE_PRIVATE const char sqlite3StrBINARY[];
-SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
-SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
-SQLITE_PRIVATE const Token sqlite3IntTokens[];
-SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
-SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
-#ifndef SQLITE_OMIT_WSD
-SQLITE_PRIVATE int sqlite3PendingByte;
-#endif
-#endif
-#ifdef VDBE_PROFILE
-SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
-#endif
-SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
-SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
-SQLITE_PRIVATE void sqlite3AlterFunctions(void);
-SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
-SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
-SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
-SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
-SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
-SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
-SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
-SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
-SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
-SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
-SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
-SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
-SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
-SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
-SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
-SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
-SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
-SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
-SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
-SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
-SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
-SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
-SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
-SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
-SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
-SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
-SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
-SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
-SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
-SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
-SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
-SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
-SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
-SQLITE_PRIVATE void sqlite3SchemaClear(void *);
-SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
-SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
-SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
-SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
-SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
-SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
-SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
-
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
-#endif
-SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
- void (*)(sqlite3_context*,int,sqlite3_value **),
- void (*)(sqlite3_context*,int,sqlite3_value **),
- void (*)(sqlite3_context*),
- void (*)(sqlite3_context*),
- void (*)(sqlite3_context*,int,sqlite3_value **),
- FuncDestructor *pDestructor
-);
-SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
-SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
-SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
-SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
-SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
-
-SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
-SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
-SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
-SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
-
-SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
-SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
-
-#ifndef SQLITE_OMIT_SUBQUERY
-SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
-#else
-# define sqlite3ExprCheckIN(x,y) SQLITE_OK
-#endif
-
-#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
-SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
-SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
- Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
-SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
-SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
-SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
-SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
-#endif
-
-/*
-** The interface to the LEMON-generated parser
-*/
-#ifndef SQLITE_AMALGAMATION
-SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
-SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
-#endif
-SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
-SQLITE_PRIVATE int sqlite3ParserFallback(int);
-#ifdef YYTRACKMAXSTACKDEPTH
-SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
-#endif
-
-SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
-#else
-# define sqlite3CloseExtensions(X)
-#endif
-
-#ifndef SQLITE_OMIT_SHARED_CACHE
-SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
-#else
- #define sqlite3TableLock(v,w,x,y,z)
-#endif
-
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
-#endif
-
-#ifdef SQLITE_OMIT_VIRTUALTABLE
-# define sqlite3VtabClear(Y)
-# define sqlite3VtabSync(X,Y) SQLITE_OK
-# define sqlite3VtabRollback(X)
-# define sqlite3VtabCommit(X)
-# define sqlite3VtabInSync(db) 0
-# define sqlite3VtabLock(X)
-# define sqlite3VtabUnlock(X)
-# define sqlite3VtabUnlockList(X)
-# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
-# define sqlite3GetVTable(X,Y) ((VTable*)0)
-#else
-SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
-SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
-SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
-SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
-SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
-SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
-SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
-SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
-SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
-SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
-SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
-SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
- sqlite3*,
- const char*,
- const sqlite3_module*,
- void*,
- void(*)(void*)
- );
-# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
-#endif
-SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
-SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
-SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
-SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
-SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
-SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
-SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
-SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
-SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
-SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
-SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
-SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
-SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
-SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
-SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
-SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
-#ifdef SQLITE_ENABLE_NORMALIZE
-SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
-#endif
-SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
-SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
-SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
-SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
-SQLITE_PRIVATE const char *sqlite3JournalModename(int);
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
-SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
-#endif
-#ifndef SQLITE_OMIT_CTE
-SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
-SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
-SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
-#else
-#define sqlite3WithPush(x,y,z)
-#define sqlite3WithDelete(x,y)
-#endif
-#ifndef SQLITE_OMIT_UPSERT
-SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
-SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
-SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
-SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
-SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
-#else
-#define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
-#define sqlite3UpsertDelete(x,y)
-#define sqlite3UpsertDup(x,y) ((Upsert*)0)
-#endif
-
-
-/* Declarations for functions in fkey.c. All of these are replaced by
-** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
-** key functionality is available. If OMIT_TRIGGER is defined but
-** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
-** this case foreign keys are parsed, but no other functionality is
-** provided (enforcement of FK constraints requires the triggers sub-system).
-*/
-#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
-SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
-SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
-SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
-SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
-SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
-SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
-#else
- #define sqlite3FkActions(a,b,c,d,e,f)
- #define sqlite3FkCheck(a,b,c,d,e,f)
- #define sqlite3FkDropTable(a,b,c)
- #define sqlite3FkOldmask(a,b) 0
- #define sqlite3FkRequired(a,b,c,d) 0
- #define sqlite3FkReferences(a) 0
-#endif
-#ifndef SQLITE_OMIT_FOREIGN_KEY
-SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
-SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
-#else
- #define sqlite3FkDelete(a,b)
- #define sqlite3FkLocateIndex(a,b,c,d,e)
-#endif
-
-
-/*
-** Available fault injectors. Should be numbered beginning with 0.
-*/
-#define SQLITE_FAULTINJECTOR_MALLOC 0
-#define SQLITE_FAULTINJECTOR_COUNT 1
-
-/*
-** The interface to the code in fault.c used for identifying "benign"
-** malloc failures. This is only present if SQLITE_UNTESTABLE
-** is not defined.
-*/
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
-SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
-#else
- #define sqlite3BeginBenignMalloc()
- #define sqlite3EndBenignMalloc()
-#endif
-
-/*
-** Allowed return values from sqlite3FindInIndex()
-*/
-#define IN_INDEX_ROWID 1 /* Search the rowid of the table */
-#define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
-#define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
-#define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
-#define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
-/*
-** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
-*/
-#define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
-#define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
-#define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
-SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
-
-SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
-SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
-#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
- || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
-SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
-#endif
-
-SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
-SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
-
-SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
-#if SQLITE_MAX_EXPR_DEPTH>0
-SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
-SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
-#else
- #define sqlite3SelectExprHeight(x) 0
- #define sqlite3ExprCheckHeight(x,y)
-#endif
-
-SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
-SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
-
-#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
-SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
-SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
-SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
-#else
- #define sqlite3ConnectionBlocked(x,y)
- #define sqlite3ConnectionUnlocked(x)
- #define sqlite3ConnectionClosed(x)
-#endif
-
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
-#endif
-#if defined(YYCOVERAGE)
-SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
-#endif
-
-/*
-** If the SQLITE_ENABLE IOTRACE exists then the global variable
-** sqlite3IoTrace is a pointer to a printf-like routine used to
-** print I/O tracing messages.
-*/
-#ifdef SQLITE_ENABLE_IOTRACE
-# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
-SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
-SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
-#else
-# define IOTRACE(A)
-# define sqlite3VdbeIOTraceSql(X)
-#endif
-
-/*
-** These routines are available for the mem2.c debugging memory allocator
-** only. They are used to verify that different "types" of memory
-** allocations are properly tracked by the system.
-**
-** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
-** the MEMTYPE_* macros defined below. The type must be a bitmask with
-** a single bit set.
-**
-** sqlite3MemdebugHasType() returns true if any of the bits in its second
-** argument match the type set by the previous sqlite3MemdebugSetType().
-** sqlite3MemdebugHasType() is intended for use inside assert() statements.
-**
-** sqlite3MemdebugNoType() returns true if none of the bits in its second
-** argument match the type set by the previous sqlite3MemdebugSetType().
-**
-** Perhaps the most important point is the difference between MEMTYPE_HEAP
-** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
-** it might have been allocated by lookaside, except the allocation was
-** too large or lookaside was already full. It is important to verify
-** that allocations that might have been satisfied by lookaside are not
-** passed back to non-lookaside free() routines. Asserts such as the
-** example above are placed on the non-lookaside free() routines to verify
-** this constraint.
-**
-** All of this is no-op for a production build. It only comes into
-** play when the SQLITE_MEMDEBUG compile-time option is used.
-*/
-#ifdef SQLITE_MEMDEBUG
-SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
-SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
-SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
-#else
-# define sqlite3MemdebugSetType(X,Y) /* no-op */
-# define sqlite3MemdebugHasType(X,Y) 1
-# define sqlite3MemdebugNoType(X,Y) 1
-#endif
-#define MEMTYPE_HEAP 0x01 /* General heap allocations */
-#define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
-#define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
-
-/*
-** Threading interface
-*/
-#if SQLITE_MAX_WORKER_THREADS>0
-SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
-SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
-#endif
-
-#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
-SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
-#endif
-#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
-SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
-#endif
-
-SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
-SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
-SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
-SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
-SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
-
-#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
-SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
-#endif
-
-#endif /* SQLITEINT_H */
-
-/************** End of sqliteInt.h *******************************************/
-/************** Begin file global.c ******************************************/
-/*
-** 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 constants.
-*/
-/* #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.
-*/
-SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
-#ifdef 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
-#ifdef 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, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
- 112,113,114,115,116,117,118,119,120,121,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,158,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,234,235,236,237,238,239, /* Ex */
- 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,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
-** Quote character 0x80
-**
-** 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))
-**
-** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
-** array. tolower() is used more often than toupper() by SQLite.
-**
-** Bit 0x40 is set if the character is 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.
-*/
-#ifdef SQLITE_ASCII
-SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
- 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, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 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, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
- 0x80, 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
-
-/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
-** compatibility for legacy applications, the URI filename capability is
-** disabled by default.
-**
-** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
-** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
-**
-** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
-** disabled. The default value may be changed by compiling with the
-** SQLITE_USE_URI symbol defined.
-**
-** URI filenames are enabled by default if SQLITE_HAS_CODEC is
-** enabled.
-*/
-#ifndef SQLITE_USE_URI
-# ifdef SQLITE_HAS_CODEC
-# define SQLITE_USE_URI 1
-# else
-# define SQLITE_USE_URI 0
-# endif
-#endif
-
-/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
-** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
-** that compile-time option is omitted.
-*/
-#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
-# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
-#else
-# if !SQLITE_ALLOW_COVERING_INDEX_SCAN
-# error "Compile-time disabling of covering index scan using the\
- -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
- Contact SQLite developers if this is a problem for you, and\
- delete this #error macro to continue with your build."
-# endif
-#endif
-
-/* The minimum PMA size is set to this value multiplied by the database
-** page size in bytes.
-*/
-#ifndef SQLITE_SORTER_PMASZ
-# define SQLITE_SORTER_PMASZ 250
-#endif
-
-/* Statement journals spill to disk when their size exceeds the following
-** threshold (in bytes). 0 means that statement journals are created and
-** written to disk immediately (the default behavior for SQLite versions
-** before 3.12.0). -1 means always keep the entire statement journal in
-** memory. (The statement journal is also always held entirely in memory
-** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
-** setting.)
-*/
-#ifndef SQLITE_STMTJRNL_SPILL
-# define SQLITE_STMTJRNL_SPILL (64*1024)
-#endif
-
-/*
-** The default lookaside-configuration, the format "SZ,N". SZ is the
-** number of bytes in each lookaside slot (should be a multiple of 8)
-** and N is the number of slots. The lookaside-configuration can be
-** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
-** or at run-time for an individual database connection using
-** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
-*/
-#ifndef SQLITE_DEFAULT_LOOKASIDE
-# define SQLITE_DEFAULT_LOOKASIDE 1200,100
-#endif
-
-
-/* The default maximum size of an in-memory database created using
-** sqlite3_deserialize()
-*/
-#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
-# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
-#endif
-
-/*
-** The following singleton contains the global configuration for
-** the SQLite library.
-*/
-SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
- SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
- 1, /* bCoreMutex */
- SQLITE_THREADSAFE==1, /* bFullMutex */
- SQLITE_USE_URI, /* bOpenUri */
- SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
- 0, /* bSmallMalloc */
- 0x7ffffffe, /* mxStrlen */
- 0, /* neverCorrupt */
- SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
- SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
- {0,0,0,0,0,0,0,0}, /* m */
- {0,0,0,0,0,0,0,0,0}, /* mutex */
- {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
- (void*)0, /* pHeap */
- 0, /* nHeap */
- 0, 0, /* mnHeap, mxHeap */
- SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
- SQLITE_MAX_MMAP_SIZE, /* mxMmap */
- (void*)0, /* pPage */
- 0, /* szPage */
- SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
- 0, /* mxParserStack */
- 0, /* sharedCacheEnabled */
- SQLITE_SORTER_PMASZ, /* szPma */
- /* All the rest should always be initialized to zero */
- 0, /* isInit */
- 0, /* inProgress */
- 0, /* isMutexInit */
- 0, /* isMallocInit */
- 0, /* isPCacheInit */
- 0, /* nRefInitMutex */
- 0, /* pInitMutex */
- 0, /* xLog */
- 0, /* pLogArg */
-#ifdef SQLITE_ENABLE_SQLLOG
- 0, /* xSqllog */
- 0, /* pSqllogArg */
-#endif
-#ifdef SQLITE_VDBE_COVERAGE
- 0, /* xVdbeBranch */
- 0, /* pVbeBranchArg */
-#endif
-#ifdef SQLITE_ENABLE_DESERIALIZE
- SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
-#endif
-#ifndef SQLITE_UNTESTABLE
- 0, /* xTestCallback */
-#endif
- 0, /* bLocaltimeFault */
- 0, /* bInternalFunctions */
- 0x7ffffffe, /* iOnceResetThreshold */
- SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
-};
-
-/*
-** Hash table for global functions - functions common to all
-** database connections. After initialization, this table is
-** read-only.
-*/
-SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
-
-/*
-** Constant tokens for values 0 and 1.
-*/
-SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
- { "0", 1 },
- { "1", 1 }
-};
-
-#ifdef VDBE_PROFILE
-/*
-** The following performance counter can be used in place of
-** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
-*/
-SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
-#endif
-
-/*
-** 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 aside
-** 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 operation will result in undefined
-** and incorrect behavior.
-*/
-#ifndef SQLITE_OMIT_WSD
-SQLITE_PRIVATE 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.
-*/
-SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
-
-/*
-** Name of the default collating sequence
-*/
-SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
-
-/************** End of global.c **********************************************/
-/************** Begin file status.c ******************************************/
-/*
-** 2008 June 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 module implements the sqlite3_status() interface and related
-** functionality.
-*/
-/* #include "sqliteInt.h" */
-/************** Include vdbeInt.h in the middle of status.c ******************/
-/************** Begin file vdbeInt.h *****************************************/
-/*
-** 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.
-*/
-#ifndef SQLITE_VDBEINT_H
-#define SQLITE_VDBEINT_H
-
-/*
-** The maximum number of times that a statement will try to reparse
-** itself before giving up and returning SQLITE_SCHEMA.
-*/
-#ifndef SQLITE_MAX_SCHEMA_RETRY
-# define SQLITE_MAX_SCHEMA_RETRY 50
-#endif
-
-/*
-** VDBE_DISPLAY_P4 is true or false depending on whether or not the
-** "explain" P4 display logic is enabled.
-*/
-#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
- || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
-# define VDBE_DISPLAY_P4 1
-#else
-# define VDBE_DISPLAY_P4 0
-#endif
-
-/*
-** 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 Bool;
-
-/* Opaque type used by code in vdbesort.c */
-typedef struct VdbeSorter VdbeSorter;
-
-/* Elements of the linked list at Vdbe.pAuxData */
-typedef struct AuxData AuxData;
-
-/* Types of VDBE cursors */
-#define CURTYPE_BTREE 0
-#define CURTYPE_SORTER 1
-#define CURTYPE_VTAB 2
-#define CURTYPE_PSEUDO 3
-
-/*
-** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
-**
-** * A b-tree cursor
-** - In the main database or in an ephemeral database
-** - On either an index or a table
-** * A sorter
-** * A virtual table
-** * A one-row "pseudotable" stored in a single register
-*/
-typedef struct VdbeCursor VdbeCursor;
-struct VdbeCursor {
- u8 eCurType; /* One of the CURTYPE_* values above */
- i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
- u8 nullRow; /* True if pointing to a row with no data */
- u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
- u8 isTable; /* True for rowid tables. False for indexes */
-#ifdef SQLITE_DEBUG
- u8 seekOp; /* Most recent seek operation on this cursor */
- u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
-#endif
- Bool isEphemeral:1; /* True for an ephemeral table */
- Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
- Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
- Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */
- Btree *pBtx; /* Separate file holding temporary table */
- i64 seqCount; /* Sequence counter */
- int *aAltMap; /* Mapping from table to index column numbers */
-
- /* Cached OP_Column parse information is only valid if cacheStatus matches
- ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
- ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
- ** the cache is out of date. */
- u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
- int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
- ** if there have been no prior seeks on the cursor. */
- /* seekResult does not distinguish between "no seeks have ever occurred
- ** on this cursor" and "the most recent seek was an exact match".
- ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
-
- /* When a new VdbeCursor is allocated, only the fields above are zeroed.
- ** The fields that follow are uninitialized, and must be individually
- ** initialized prior to first use. */
- VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
- union {
- BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
- sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
- VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
- } uc;
- KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
- u32 iHdrOffset; /* Offset to next unparsed byte of the header */
- Pgno pgnoRoot; /* Root page of the open btree cursor */
- i16 nField; /* Number of fields in the header */
- u16 nHdrParsed; /* Number of header fields parsed so far */
- i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
- u32 *aOffset; /* Pointer to aType[nField] */
- const u8 *aRow; /* Data for the current row, if all on one page */
- u32 payloadSize; /* Total number of bytes in the record */
- u32 szRow; /* Byte available in aRow */
-#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
- u64 maskUsed; /* Mask of columns used by this cursor */
-#endif
-
- /* 2*nField extra array elements allocated for aType[], beyond the one
- ** static element declared in the structure. nField total array slots for
- ** aType[] and nField+1 array slots for aOffset[] */
- u32 aType[1]; /* Type values record decode. MUST BE LAST */
-};
-
-
-/*
-** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
-*/
-#define CACHE_STALE 0
-
-/*
-** 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;
-struct VdbeFrame {
- Vdbe *v; /* VM this frame belongs to */
- VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
- Op *aOp; /* Program instructions for parent frame */
- i64 *anExec; /* Event counters from parent frame */
- Mem *aMem; /* Array of memory cells for parent frame */
- VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
- u8 *aOnce; /* Bitmask used by OP_Once */
- void *token; /* Copy of SubProgram.token */
- i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
- AuxData *pAuxData; /* Linked list of auxdata allocations */
-#if SQLITE_DEBUG
- u32 iFrameMagic; /* magic number for sanity checking */
-#endif
- int nCursor; /* Number of entries in apCsr */
- int pc; /* Program Counter in parent (calling) frame */
- int nOp; /* Size of aOp array */
- int nMem; /* Number of entries in aMem */
- int nChildMem; /* Number of memory cells for child frame */
- int nChildCsr; /* Number of cursors for child frame */
- int nChange; /* Statement changes (Vdbe.nChange) */
- int nDbChange; /* Value of db->nChange */
-};
-
-/* Magic number for sanity checking on VdbeFrame objects */
-#define SQLITE_FRAME_MAGIC 0x879fb71e
-
-/*
-** Return a pointer to the array of registers allocated for use
-** by a VdbeFrame.
-*/
-#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
-
-/*
-** 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.
-*/
-struct sqlite3_value {
- union MemValue {
- double r; /* Real value used when MEM_Real is set in flags */
- i64 i; /* Integer value used when MEM_Int is set in flags */
- int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
- const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
- FuncDef *pDef; /* Used only when flags==MEM_Agg */
- } u;
- u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
- u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
- u8 eSubtype; /* Subtype for this value */
- int n; /* Number of characters in string value, excluding '\0' */
- char *z; /* String or BLOB value */
- /* ShallowCopy only needs to copy the information above */
- char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
- int szMalloc; /* Size of the zMalloc allocation */
- u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
- sqlite3 *db; /* The associated database connection */
- void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
-#ifdef SQLITE_DEBUG
- Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
- u16 mScopyFlags; /* flags value immediately after the shallow copy */
-#endif
-};
-
-/*
-** Size of struct Mem not including the Mem.zMalloc member or anything that
-** follows.
-*/
-#define MEMCELLSIZE offsetof(Mem,zMalloc)
-
-/* 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.
-** For a pointer type created using sqlite3_bind_pointer() or
-** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
-**
-** 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 (or a pointer) */
-#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_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */
-#define MEM_AffMask 0x003f /* Mask of affinity bits */
-#define MEM_FromBind 0x0040 /* Value originates from sqlite3_bind() */
-#define MEM_Undefined 0x0080 /* Value is undefined */
-#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
-#define MEM_TypeMask 0xc1bf /* Mask of type bits */
-
-
-/* Whenever Mem contains a valid string or blob representation, one of
-** the following flags must be set to determine the memory management
-** policy for Mem.z. The MEM_Term flag tells us whether or not the
-** string is \000 or \u0000 terminated
-*/
-#define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
-#define MEM_Dyn 0x0400 /* Need to call Mem.xDel() 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 */
-#define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
-#ifdef SQLITE_OMIT_INCRBLOB
- #undef MEM_Zero
- #define MEM_Zero 0x0000
-#endif
-
-/* Return TRUE if Mem X contains dynamically allocated content - anything
-** that needs to be deallocated to avoid a leak.
-*/
-#define VdbeMemDynamic(X) \
- (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
-
-/*
-** 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)
-
-/*
-** True if Mem X is a NULL-nochng type.
-*/
-#define MemNullNochng(X) \
- ((X)->flags==(MEM_Null|MEM_Zero) && (X)->n==0 && (X)->u.nZero==0)
-
-/*
-** Return true if a memory cell is not marked as invalid. This macro
-** is for use inside assert() statements only.
-*/
-#ifdef SQLITE_DEBUG
-#define memIsValid(M) ((M)->flags & MEM_Undefined)==0
-#endif
-
-/*
-** Each auxiliary data pointer stored by a user defined function
-** implementation calling sqlite3_set_auxdata() is stored in an instance
-** of this structure. All such structures associated with a single VM
-** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
-** when the VM is halted (if not before).
-*/
-struct AuxData {
- int iAuxOp; /* Instruction number of OP_Function opcode */
- int iAuxArg; /* Index of function argument. */
- void *pAux; /* Aux data pointer */
- void (*xDeleteAux)(void*); /* Destructor for the aux data */
- AuxData *pNextAux; /* Next element in list */
-};
-
-/*
-** The "context" argument for an 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.
-*/
-struct sqlite3_context {
- Mem *pOut; /* The return value is stored here */
- FuncDef *pFunc; /* Pointer to function information */
- Mem *pMem; /* Memory cell used to store aggregate context */
- Vdbe *pVdbe; /* The VM that owns this context */
- int iOp; /* Instruction number of OP_Function */
- int isError; /* Error code returned by the function. */
- u8 skipFlag; /* Skip accumulator loading if true */
- u8 argc; /* Number of arguments */
- sqlite3_value *argv[1]; /* Argument set */
-};
-
-/* A bitfield type for use inside of structures. Always follow with :N where
-** N is the number of bits.
-*/
-typedef unsigned bft; /* Bit Field Type */
-
-/* The ScanStatus object holds a single value for the
-** sqlite3_stmt_scanstatus() interface.
-*/
-typedef struct ScanStatus ScanStatus;
-struct ScanStatus {
- int addrExplain; /* OP_Explain for loop */
- int addrLoop; /* Address of "loops" counter */
- int addrVisit; /* Address of "rows visited" counter */
- int iSelectID; /* The "Select-ID" for this loop */
- LogEst nEst; /* Estimated output rows per loop */
- char *zName; /* Name of table or index */
-};
-
-/* The DblquoteStr object holds the text of a double-quoted
-** string for a prepared statement. A linked list of these objects
-** is constructed during statement parsing and is held on Vdbe.pDblStr.
-** When computing a normalized SQL statement for an SQL statement, that
-** list is consulted for each double-quoted identifier to see if the
-** identifier should really be a string literal.
-*/
-typedef struct DblquoteStr DblquoteStr;
-struct DblquoteStr {
- DblquoteStr *pNextStr; /* Next string literal in the list */
- char z[8]; /* Dequoted value for the string */
-};
-
-/*
-** 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.
-*/
-struct Vdbe {
- sqlite3 *db; /* The database connection that owns this statement */
- Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
- Parse *pParse; /* Parsing context used to create this Vdbe */
- ynVar nVar; /* Number of entries in aVar[] */
- u32 magic; /* Magic number for sanity checking */
- int nMem; /* Number of memory locations currently allocated */
- int nCursor; /* Number of slots in apCsr[] */
- u32 cacheCtr; /* VdbeCursor row cache generation counter */
- int pc; /* The program counter */
- int rc; /* Value to return */
- int nChange; /* Number of db changes made since last reset */
- int iStatement; /* Statement number (or 0 if has no opened stmt) */
- i64 iCurrentTime; /* Value of julianday('now') for this statement */
- i64 nFkConstraint; /* Number of imm. FK constraints this VM */
- i64 nStmtDefCons; /* Number of def. constraints when stmt started */
- i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
- Mem *aMem; /* The memory locations */
- Mem **apArg; /* Arguments to currently executing user function */
- VdbeCursor **apCsr; /* One element of this array for each open cursor */
- Mem *aVar; /* Values for the OP_Variable opcode. */
-
- /* When allocating a new Vdbe object, all of the fields below should be
- ** initialized to zero or NULL */
-
- Op *aOp; /* Space to hold the virtual machine's program */
- int nOp; /* Number of instructions in the program */
- int nOpAlloc; /* Slots allocated for aOp[] */
- Mem *aColName; /* Column names to return */
- Mem *pResultSet; /* Pointer to an array of results */
- char *zErrMsg; /* Error message written here */
- VList *pVList; /* Name of variables */
-#ifndef SQLITE_OMIT_TRACE
- i64 startTime; /* Time when query started - used for profiling */
-#endif
-#ifdef SQLITE_DEBUG
- int rcApp; /* errcode set by sqlite3_result_error_code() */
- u32 nWrite; /* Number of write operations that have occurred */
-#endif
- u16 nResColumn; /* Number of columns in one row of the result set */
- u8 errorAction; /* Recovery action to do in case of an error */
- u8 minWriteFileFormat; /* Minimum file format for writable database files */
- u8 prepFlags; /* SQLITE_PREPARE_* flags */
- bft expired:2; /* 1: recompile VM immediately 2: when convenient */
- bft explain:2; /* True if EXPLAIN present on SQL command */
- bft doingRerun:1; /* True if rerunning after an auto-reprepare */
- bft changeCntOn:1; /* True to update the change-counter */
- bft runOnlyOnce:1; /* Automatically expire on reset */
- bft usesStmtJournal:1; /* True if uses a statement journal */
- bft readOnly:1; /* True for statements that do not write */
- bft bIsReader:1; /* True for statements that read */
- yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
- yDbMask lockMask; /* Subset of btreeMask that requires a lock */
- u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
- char *zSql; /* Text of the SQL statement that generated this */
-#ifdef SQLITE_ENABLE_NORMALIZE
- char *zNormSql; /* Normalization of the associated SQL statement */
- DblquoteStr *pDblStr; /* List of double-quoted string literals */
-#endif
- void *pFree; /* Free this when deleting the vdbe */
- VdbeFrame *pFrame; /* Parent frame */
- VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
- int nFrame; /* Number of frames in pFrame list */
- u32 expmask; /* Binding to these vars invalidates VM */
- SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
- AuxData *pAuxData; /* Linked list of auxdata allocations */
-#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
- i64 *anExec; /* Number of times each op has been executed */
- int nScan; /* Entries in aScan[] */
- ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
-#endif
-};
-
-/*
-** The following are allowed values for Vdbe.magic
-*/
-#define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
-#define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
-#define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
-#define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
-#define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
-
-/*
-** Structure used to store the context required by the
-** sqlite3_preupdate_*() API functions.
-*/
-struct PreUpdate {
- Vdbe *v;
- VdbeCursor *pCsr; /* Cursor to read old values from */
- int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
- u8 *aRecord; /* old.* database record */
- KeyInfo keyinfo;
- UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
- UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
- int iNewReg; /* Register for new.* values */
- i64 iKey1; /* First key value passed to hook */
- i64 iKey2; /* Second key value passed to hook */
- Mem *aNew; /* Array of new.* values */
- Table *pTab; /* Schema object being upated */
- Index *pPk; /* PK index if pTab is WITHOUT ROWID */
-};
-
-/*
-** Function prototypes
-*/
-SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
-SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
-void sqliteVdbePopStack(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
-SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
-SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
-SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
-SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
-SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
-SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
-SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
-
-int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
-SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
-SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
-SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
-#ifndef SQLITE_OMIT_EXPLAIN
-SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
-#endif
-SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
-SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
-SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
-SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
-SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
-SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
-#ifdef SQLITE_OMIT_FLOATING_POINT
-# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
-#else
-SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
-#endif
-SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
-SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
-SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
-SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
-#endif
-SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
-SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
-SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
-SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
-SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
-SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
-SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
-SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
-SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
-#ifndef SQLITE_OMIT_WINDOWFUNC
-SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
-#endif
-#ifndef SQLITE_OMIT_EXPLAIN
-SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
-#endif
-SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
-SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
-SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
-#endif
-SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
-SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
-SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
-#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
-SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
-#endif
-SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
-
-SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
-SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
-SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
-SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
-SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
-SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
-SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
-SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
-
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
-SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
-#else
-# define sqlite3VdbeIncrWriteCounter(V,C)
-# define sqlite3VdbeAssertAbortable(V)
-#endif
-
-#if !defined(SQLITE_OMIT_SHARED_CACHE)
-SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
-#else
-# define sqlite3VdbeEnter(X)
-#endif
-
-#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
-SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
-#else
-# define sqlite3VdbeLeave(X)
-#endif
-
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
-SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
-#endif
-
-#ifndef SQLITE_OMIT_FOREIGN_KEY
-SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
-#else
-# define sqlite3VdbeCheckFk(p,i) 0
-#endif
-
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
-SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
-#endif
-#ifndef SQLITE_OMIT_UTF16
-SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
-SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
-#endif
-
-#ifndef SQLITE_OMIT_INCRBLOB
-SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
- #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
-#else
- #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
- #define ExpandBlob(P) SQLITE_OK
-#endif
-
-#endif /* !defined(SQLITE_VDBEINT_H) */
-
-/************** End of vdbeInt.h *********************************************/
-/************** Continuing where we left off in status.c *********************/
-
-/*
-** Variables in which to record status information.
-*/
-#if SQLITE_PTRSIZE>4
-typedef sqlite3_int64 sqlite3StatValueType;
-#else
-typedef u32 sqlite3StatValueType;
-#endif
-typedef struct sqlite3StatType sqlite3StatType;
-static SQLITE_WSD struct sqlite3StatType {
- sqlite3StatValueType nowValue[10]; /* Current value */
- sqlite3StatValueType mxValue[10]; /* Maximum value */
-} sqlite3Stat = { {0,}, {0,} };
-
-/*
-** Elements of sqlite3Stat[] are protected by either the memory allocator
-** mutex, or by the pcache1 mutex. The following array determines which.
-*/
-static const char statMutex[] = {
- 0, /* SQLITE_STATUS_MEMORY_USED */
- 1, /* SQLITE_STATUS_PAGECACHE_USED */
- 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
- 0, /* SQLITE_STATUS_SCRATCH_USED */
- 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
- 0, /* SQLITE_STATUS_MALLOC_SIZE */
- 0, /* SQLITE_STATUS_PARSER_STACK */
- 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
- 0, /* SQLITE_STATUS_SCRATCH_SIZE */
- 0, /* SQLITE_STATUS_MALLOC_COUNT */
-};
-
-
-/* The "wsdStat" macro will resolve to the status information
-** 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 "sqlite3Stat" state vector declared above.
-*/
-#ifdef SQLITE_OMIT_WSD
-# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
-# define wsdStat x[0]
-#else
-# define wsdStatInit
-# define wsdStat sqlite3Stat
-#endif
-
-/*
-** Return the current value of a status parameter. The caller must
-** be holding the appropriate mutex.
-*/
-SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
- wsdStatInit;
- assert( op>=0 && op=0 && op=0 && op=0 && opwsdStat.mxValue[op] ){
- wsdStat.mxValue[op] = wsdStat.nowValue[op];
- }
-}
-SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
- wsdStatInit;
- assert( N>=0 );
- assert( op>=0 && op=0 && op=0 );
- newValue = (sqlite3StatValueType)X;
- assert( op>=0 && op=0 && opwsdStat.mxValue[op] ){
- wsdStat.mxValue[op] = newValue;
- }
-}
-
-/*
-** Query status information.
-*/
-SQLITE_API int sqlite3_status64(
- int op,
- sqlite3_int64 *pCurrent,
- sqlite3_int64 *pHighwater,
- int resetFlag
-){
- sqlite3_mutex *pMutex;
- wsdStatInit;
- if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
- return SQLITE_MISUSE_BKPT;
- }
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
-#endif
- pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
- sqlite3_mutex_enter(pMutex);
- *pCurrent = wsdStat.nowValue[op];
- *pHighwater = wsdStat.mxValue[op];
- if( resetFlag ){
- wsdStat.mxValue[op] = wsdStat.nowValue[op];
- }
- sqlite3_mutex_leave(pMutex);
- (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
- return SQLITE_OK;
-}
-SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
- sqlite3_int64 iCur = 0, iHwtr = 0;
- int rc;
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
-#endif
- rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
- if( rc==0 ){
- *pCurrent = (int)iCur;
- *pHighwater = (int)iHwtr;
- }
- return rc;
-}
-
-/*
-** Return the number of LookasideSlot elements on the linked list
-*/
-static u32 countLookasideSlots(LookasideSlot *p){
- u32 cnt = 0;
- while( p ){
- p = p->pNext;
- cnt++;
- }
- return cnt;
-}
-
-/*
-** Count the number of slots of lookaside memory that are outstanding
-*/
-SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
- u32 nInit = countLookasideSlots(db->lookaside.pInit);
- u32 nFree = countLookasideSlots(db->lookaside.pFree);
- if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
- return db->lookaside.nSlot - (nInit+nFree);
-}
-
-/*
-** Query status information for a single database connection
-*/
-SQLITE_API int sqlite3_db_status(
- sqlite3 *db, /* The database connection whose status is desired */
- int op, /* Status verb */
- int *pCurrent, /* Write current value here */
- int *pHighwater, /* Write high-water mark here */
- int resetFlag /* Reset high-water mark if true */
-){
- int rc = SQLITE_OK; /* Return code */
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
- return SQLITE_MISUSE_BKPT;
- }
-#endif
- sqlite3_mutex_enter(db->mutex);
- switch( op ){
- case SQLITE_DBSTATUS_LOOKASIDE_USED: {
- *pCurrent = sqlite3LookasideUsed(db, pHighwater);
- if( resetFlag ){
- LookasideSlot *p = db->lookaside.pFree;
- if( p ){
- while( p->pNext ) p = p->pNext;
- p->pNext = db->lookaside.pInit;
- db->lookaside.pInit = db->lookaside.pFree;
- db->lookaside.pFree = 0;
- }
- }
- break;
- }
-
- case SQLITE_DBSTATUS_LOOKASIDE_HIT:
- case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
- case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
- testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
- testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
- testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
- assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
- assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
- *pCurrent = 0;
- *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
- if( resetFlag ){
- db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
- }
- break;
- }
-
- /*
- ** Return an approximation for the amount of memory currently used
- ** by all pagers associated with the given database connection. The
- ** highwater mark is meaningless and is returned as zero.
- */
- case SQLITE_DBSTATUS_CACHE_USED_SHARED:
- case SQLITE_DBSTATUS_CACHE_USED: {
- int totalUsed = 0;
- int i;
- sqlite3BtreeEnterAll(db);
- for(i=0; inDb; i++){
- Btree *pBt = db->aDb[i].pBt;
- if( pBt ){
- Pager *pPager = sqlite3BtreePager(pBt);
- int nByte = sqlite3PagerMemUsed(pPager);
- if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
- nByte = nByte / sqlite3BtreeConnectionCount(pBt);
- }
- totalUsed += nByte;
- }
- }
- sqlite3BtreeLeaveAll(db);
- *pCurrent = totalUsed;
- *pHighwater = 0;
- break;
- }
-
- /*
- ** *pCurrent gets an accurate estimate of the amount of memory used
- ** to store the schema for all databases (main, temp, and any ATTACHed
- ** databases. *pHighwater is set to zero.
- */
- case SQLITE_DBSTATUS_SCHEMA_USED: {
- int i; /* Used to iterate through schemas */
- int nByte = 0; /* Used to accumulate return value */
-
- sqlite3BtreeEnterAll(db);
- db->pnBytesFreed = &nByte;
- for(i=0; inDb; i++){
- Schema *pSchema = db->aDb[i].pSchema;
- if( ALWAYS(pSchema!=0) ){
- HashElem *p;
-
- nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
- pSchema->tblHash.count
- + pSchema->trigHash.count
- + pSchema->idxHash.count
- + pSchema->fkeyHash.count
- );
- nByte += sqlite3_msize(pSchema->tblHash.ht);
- nByte += sqlite3_msize(pSchema->trigHash.ht);
- nByte += sqlite3_msize(pSchema->idxHash.ht);
- nByte += sqlite3_msize(pSchema->fkeyHash.ht);
-
- for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
- sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
- }
- for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
- sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
- }
- }
- }
- db->pnBytesFreed = 0;
- sqlite3BtreeLeaveAll(db);
-
- *pHighwater = 0;
- *pCurrent = nByte;
- break;
- }
-
- /*
- ** *pCurrent gets an accurate estimate of the amount of memory used
- ** to store all prepared statements.
- ** *pHighwater is set to zero.
- */
- case SQLITE_DBSTATUS_STMT_USED: {
- struct Vdbe *pVdbe; /* Used to iterate through VMs */
- int nByte = 0; /* Used to accumulate return value */
-
- db->pnBytesFreed = &nByte;
- for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
- sqlite3VdbeClearObject(db, pVdbe);
- sqlite3DbFree(db, pVdbe);
- }
- db->pnBytesFreed = 0;
-
- *pHighwater = 0; /* IMP: R-64479-57858 */
- *pCurrent = nByte;
-
- break;
- }
-
- /*
- ** Set *pCurrent to the total cache hits or misses encountered by all
- ** pagers the database handle is connected to. *pHighwater is always set
- ** to zero.
- */
- case SQLITE_DBSTATUS_CACHE_SPILL:
- op = SQLITE_DBSTATUS_CACHE_WRITE+1;
- /* Fall through into the next case */
- case SQLITE_DBSTATUS_CACHE_HIT:
- case SQLITE_DBSTATUS_CACHE_MISS:
- case SQLITE_DBSTATUS_CACHE_WRITE:{
- int i;
- int nRet = 0;
- assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
- assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
-
- for(i=0; inDb; i++){
- if( db->aDb[i].pBt ){
- Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
- sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
- }
- }
- *pHighwater = 0; /* IMP: R-42420-56072 */
- /* IMP: R-54100-20147 */
- /* IMP: R-29431-39229 */
- *pCurrent = nRet;
- break;
- }
-
- /* Set *pCurrent to non-zero if there are unresolved deferred foreign
- ** key constraints. Set *pCurrent to zero if all foreign key constraints
- ** have been satisfied. The *pHighwater is always set to zero.
- */
- case SQLITE_DBSTATUS_DEFERRED_FKS: {
- *pHighwater = 0; /* IMP: R-11967-56545 */
- *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
- break;
- }
-
- default: {
- rc = SQLITE_ERROR;
- }
- }
- sqlite3_mutex_leave(db->mutex);
- return rc;
-}
-
-/************** End of status.c **********************************************/
-/************** Begin file date.c ********************************************/
-/*
-** 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 implementation 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
-** ISBN 0-943396-61-1
-** Willmann-Bell, Inc
-** Richmond, Virginia (USA)
-*/
-/* #include "sqliteInt.h" */
-/* #include */
-/* #include */
-#include
-
-#ifndef SQLITE_OMIT_DATETIME_FUNCS
-
-/*
-** The MSVC CRT on Windows CE may not have a localtime() function.
-** So declare a substitute. The substitute function itself is
-** defined in "os_win.c".
-*/
-#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
- (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
-struct tm *__cdecl localtime(const time_t *);
-#endif
-
-/*
-** A structure for holding a single date and time.
-*/
-typedef struct DateTime DateTime;
-struct DateTime {
- sqlite3_int64 iJD; /* The julian day number times 86400000 */
- int Y, M, D; /* Year, month, and day */
- int h, m; /* Hour and minutes */
- int tz; /* Timezone offset in minutes */
- double s; /* Seconds */
- char validJD; /* True (1) if iJD is valid */
- char rawS; /* Raw numeric value stored in s */
- char validYMD; /* True (1) if Y,M,D are valid */
- char validHMS; /* True (1) if h,m,s are valid */
- char validTZ; /* True (1) if tz is valid */
- char tzSet; /* Timezone was set explicitly */
- char isError; /* An overflow has occurred */
-};
-
-
-/*
-** Convert zDate into one or more integers according to the conversion
-** specifier zFormat.
-**
-** zFormat[] contains 4 characters for each integer converted, except for
-** the last integer which is specified by three characters. The meaning
-** of a four-character format specifiers ABCD is:
-**
-** A: number of digits to convert. Always "2" or "4".
-** B: minimum value. Always "0" or "1".
-** C: maximum value, decoded as:
-** a: 12
-** b: 14
-** c: 24
-** d: 31
-** e: 59
-** f: 9999
-** D: the separator character, or \000 to indicate this is the
-** last number to convert.
-**
-** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
-** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
-** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
-** the 2-digit day which is the last integer in the set.
-**
-** The function returns the number of successful conversions.
-*/
-static int getDigits(const char *zDate, const char *zFormat, ...){
- /* The aMx[] array translates the 3rd character of each format
- ** spec into a max size: a b c d e f */
- static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
- va_list ap;
- int cnt = 0;
- char nextC;
- va_start(ap, zFormat);
- do{
- char N = zFormat[0] - '0';
- char min = zFormat[1] - '0';
- int val = 0;
- u16 max;
-
- assert( zFormat[2]>='a' && zFormat[2]<='f' );
- max = aMx[zFormat[2] - 'a'];
- nextC = zFormat[3];
- val = 0;
- while( N-- ){
- if( !sqlite3Isdigit(*zDate) ){
- goto end_getDigits;
- }
- val = val*10 + *zDate - '0';
- zDate++;
- }
- if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
- goto end_getDigits;
- }
- *va_arg(ap,int*) = val;
- zDate++;
- cnt++;
- zFormat += 4;
- }while( nextC );
-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(const char *zDate, DateTime *p){
- int sgn = 0;
- int nHr, nMn;
- int c;
- while( sqlite3Isspace(*zDate) ){ zDate++; }
- p->tz = 0;
- c = *zDate;
- if( c=='-' ){
- sgn = -1;
- }else if( c=='+' ){
- sgn = +1;
- }else if( c=='Z' || c=='z' ){
- zDate++;
- goto zulu_time;
- }else{
- return c!=0;
- }
- zDate++;
- if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
- return 1;
- }
- zDate += 5;
- p->tz = sgn*(nMn + nHr*60);
-zulu_time:
- while( sqlite3Isspace(*zDate) ){ zDate++; }
- p->tzSet = 1;
- return *zDate!=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(const char *zDate, DateTime *p){
- int h, m, s;
- double ms = 0.0;
- if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
- return 1;
- }
- zDate += 5;
- if( *zDate==':' ){
- zDate++;
- if( getDigits(zDate, "20e", &s)!=1 ){
- return 1;
- }
- zDate += 2;
- if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
- double rScale = 1.0;
- zDate++;
- while( sqlite3Isdigit(*zDate) ){
- ms = ms*10.0 + *zDate - '0';
- rScale *= 10.0;
- zDate++;
- }
- ms /= rScale;
- }
- }else{
- s = 0;
- }
- p->validJD = 0;
- p->rawS = 0;
- p->validHMS = 1;
- p->h = h;
- p->m = m;
- p->s = s + ms;
- if( parseTimezone(zDate, p) ) return 1;
- p->validTZ = (p->tz!=0)?1:0;
- return 0;
-}
-
-/*
-** Put the DateTime object into its error state.
-*/
-static void datetimeError(DateTime *p){
- memset(p, 0, sizeof(*p));
- p->isError = 1;
-}
-
-/*
-** 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 ) return;
- if( p->validYMD ){
- 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( Y<-4713 || Y>9999 || p->rawS ){
- datetimeError(p);
- return;
- }
- if( M<=2 ){
- Y--;
- M += 12;
- }
- A = Y/100;
- B = 2 - A + (A/4);
- X1 = 36525*(Y+4716)/100;
- X2 = 306001*(M+1)/10000;
- p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
- p->validJD = 1;
- if( p->validHMS ){
- p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
- if( p->validTZ ){
- 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(const char *zDate, DateTime *p){
- int Y, M, D, neg;
-
- if( zDate[0]=='-' ){
- zDate++;
- neg = 1;
- }else{
- neg = 0;
- }
- if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
- return 1;
- }
- zDate += 10;
- while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
- if( parseHhMmSs(zDate, p)==0 ){
- /* We got the time */
- }else if( *zDate==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 ){
- computeJD(p);
- }
- return 0;
-}
-
-/*
-** Set the time to the current time reported by the VFS.
-**
-** Return the number of errors.
-*/
-static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
- p->iJD = sqlite3StmtCurrentTime(context);
- if( p->iJD>0 ){
- p->validJD = 1;
- return 0;
- }else{
- return 1;
- }
-}
-
-/*
-** Input "r" is a numeric quantity which might be a julian day number,
-** or the number of seconds since 1970. If the value if r is within
-** range of a julian day number, install it as such and set validJD.
-** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
-*/
-static void setRawDateNumber(DateTime *p, double r){
- p->s = r;
- p->rawS = 1;
- if( r>=0.0 && r<5373484.5 ){
- p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
- p->validJD = 1;
- }
-}
-
-/*
-** Attempt to parse the given string into a julian day number. Return
-** the number of errors.
-**
-** The following are acceptable forms for the input string:
-**
-** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
-** DDDD.DD
-** now
-**
-** In the first form, the +/-HH:MM is always optional. The fractional
-** seconds extension (the ".FFF") is optional. The seconds portion
-** (":SS.FFF") is option. The year and date can be omitted as long
-** as there is a time string. The time string can be omitted as long
-** as there is a year and date.
-*/
-static int parseDateOrTime(
- sqlite3_context *context,
- const char *zDate,
- DateTime *p
-){
- double r;
- if( parseYyyyMmDd(zDate,p)==0 ){
- return 0;
- }else if( parseHhMmSs(zDate, p)==0 ){
- return 0;
- }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
- return setDateTimeToCurrent(context, p);
- }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
- setRawDateNumber(p, r);
- return 0;
- }
- return 1;
-}
-
-/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
-** Multiplying this by 86400000 gives 464269060799999 as the maximum value
-** for DateTime.iJD.
-**
-** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
-** such a large integer literal, so we have to encode it.
-*/
-#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
-
-/*
-** Return TRUE if the given julian day number is within range.
-**
-** The input is the JulianDay times 86400000.
-*/
-static int validJulianDay(sqlite3_int64 iJD){
- return iJD>=0 && iJD<=INT_464269060799999;
-}
-
-/*
-** 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 ) return;
- if( !p->validJD ){
- p->Y = 2000;
- p->M = 1;
- p->D = 1;
- }else if( !validJulianDay(p->iJD) ){
- datetimeError(p);
- return;
- }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 = (36525*(C&32767))/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 ) 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->rawS = 0;
- 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;
-}
-
-#ifndef SQLITE_OMIT_LOCALTIME
-/*
-** On recent Windows platforms, the localtime_s() function is available
-** as part of the "Secure CRT". It is essentially equivalent to
-** localtime_r() available under most POSIX platforms, except that the
-** order of the parameters is reversed.
-**
-** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
-**
-** If the user has not indicated to use localtime_r() or localtime_s()
-** already, check for an MSVC build environment that provides
-** localtime_s().
-*/
-#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
- && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
-#undef HAVE_LOCALTIME_S
-#define HAVE_LOCALTIME_S 1
-#endif
-
-/*
-** 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.
-**
-** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
-** library function localtime_r() is used to assist in the calculation of
-** local time.
-*/
-static int osLocaltime(time_t *t, struct tm *pTm){
- int rc;
-#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
- struct tm *pX;
-#if SQLITE_THREADSAFE>0
- sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
-#endif
- sqlite3_mutex_enter(mutex);
- pX = localtime(t);
-#ifndef SQLITE_UNTESTABLE
- if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
-#endif
- if( pX ) *pTm = *pX;
- sqlite3_mutex_leave(mutex);
- rc = pX==0;
-#else
-#ifndef SQLITE_UNTESTABLE
- if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
-#endif
-#if 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 */
-
-
-#ifndef 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 */
- int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
-){
- DateTime x, y;
- time_t t;
- struct tm sLocal;
-
- /* 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 ){
- /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
- ** works for years between 1970 and 2037. For dates outside this range,
- ** SQLite attempts to map the year into an equivalent year within this
- ** range, do the calculation, then map the year back.
- */
- 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 = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
- if( osLocaltime(&t, &sLocal) ){
- 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.rawS = 0;
- y.validTZ = 0;
- y.isError = 0;
- computeJD(&y);
- *pRc = SQLITE_OK;
- return y.iJD - x.iJD;
-}
-#endif /* SQLITE_OMIT_LOCALTIME */
-
-/*
-** The following table defines various date transformations of the form
-**
-** 'NNN days'
-**
-** Where NNN is an arbitrary floating-point number and "days" can be one
-** of several units of time.
-*/
-static const struct {
- u8 eType; /* Transformation type code */
- u8 nName; /* Length of th name */
- char *zName; /* Name of the transformation */
- double rLimit; /* Maximum NNN value for this transform */
- double rXform; /* Constant used for this transform */
-} aXformType[] = {
- { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
- { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
- { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
- { 0, 3, "day", 5373485.0, 86400000.0 },
- { 1, 5, "month", 176546.0, 30.0*86400000.0 },
- { 2, 4, "year", 14713.0, 365.0*86400000.0 },
-};
-
-/*
-** 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, /* Function context */
- const char *z, /* The text of the modifier */
- int n, /* Length of zMod in bytes */
- DateTime *p /* The date/time value to be modified */
-){
- int rc = 1;
- double r;
- switch(sqlite3UpperToLower[(u8)z[0]] ){
-#ifndef SQLITE_OMIT_LOCALTIME
- case 'l': {
- /* localtime
- **
- ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
- ** show local time.
- */
- if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
- computeJD(p);
- p->iJD += localtimeOffset(p, pCtx, &rc);
- clearYMD_HMS_TZ(p);
- }
- break;
- }
-#endif
- case 'u': {
- /*
- ** unixepoch
- **
- ** Treat the current value of p->s as the number of
- ** seconds since 1970. Convert to a real julian day number.
- */
- if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
- r = p->s*1000.0 + 210866760000000.0;
- if( r>=0.0 && r<464269060800000.0 ){
- clearYMD_HMS_TZ(p);
- p->iJD = (sqlite3_int64)r;
- p->validJD = 1;
- p->rawS = 0;
- rc = 0;
- }
- }
-#ifndef SQLITE_OMIT_LOCALTIME
- else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
- if( p->tzSet==0 ){
- sqlite3_int64 c1;
- computeJD(p);
- c1 = localtimeOffset(p, pCtx, &rc);
- if( rc==SQLITE_OK ){
- p->iJD -= c1;
- clearYMD_HMS_TZ(p);
- p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
- }
- p->tzSet = 1;
- }else{
- rc = SQLITE_OK;
- }
- }
-#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( sqlite3_strnicmp(z, "weekday ", 8)==0
- && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
- && (n=(int)r)==r && n>=0 && r<7 ){
- sqlite3_int64 Z;
- computeYMD_HMS(p);
- p->validTZ = 0;
- p->validJD = 0;
- computeJD(p);
- Z = ((p->iJD + 129600000)/86400000) % 7;
- if( Z>n ) Z -= 7;
- p->iJD += (n - Z)*86400000;
- clearYMD_HMS_TZ(p);
- rc = 0;
- }
- break;
- }
- case 's': {
- /*
- ** start of TTTTT
- **
- ** Move the date backwards to the beginning of the current day,
- ** or month or year.
- */
- if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
- if( !p->validJD && !p->validYMD && !p->validHMS ) break;
- z += 9;
- computeYMD(p);
- p->validHMS = 1;
- p->h = p->m = 0;
- p->s = 0.0;
- p->rawS = 0;
- p->validTZ = 0;
- p->validJD = 0;
- if( sqlite3_stricmp(z,"month")==0 ){
- p->D = 1;
- rc = 0;
- }else if( sqlite3_stricmp(z,"year")==0 ){
- p->M = 1;
- p->D = 1;
- rc = 0;
- }else if( sqlite3_stricmp(z,"day")==0 ){
- 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;
- int i;
- for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
- if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
- rc = 1;
- break;
- }
- 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.
- */
- const char *z2 = z;
- DateTime tx;
- sqlite3_int64 day;
- if( !sqlite3Isdigit(*z2) ) z2++;
- memset(&tx, 0, sizeof(tx));
- if( parseHhMmSs(z2, &tx) ) 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;
- }
-
- /* If control reaches this point, it means the transformation is
- ** one of the forms like "+NNN days". */
- z += n;
- while( sqlite3Isspace(*z) ) z++;
- n = sqlite3Strlen30(z);
- if( n>10 || n<3 ) break;
- if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
- computeJD(p);
- rc = 1;
- rRounder = r<0 ? -0.5 : +0.5;
- for(i=0; i-aXformType[i].rLimit && rM += (int)r;
- x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
- p->Y += x;
- p->M -= x*12;
- p->validJD = 0;
- r -= (int)r;
- break;
- }
- case 2: { /* Special processing to add years */
- int y = (int)r;
- computeYMD_HMS(p);
- p->Y += y;
- p->validJD = 0;
- r -= (int)r;
- break;
- }
- }
- computeJD(p);
- p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
- rc = 0;
- break;
- }
- }
- 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,
- DateTime *p
-){
- int i, n;
- const unsigned char *z;
- int eType;
- memset(p, 0, sizeof(*p));
- if( argc==0 ){
- return setDateTimeToCurrent(context, p);
- }
- if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
- || eType==SQLITE_INTEGER ){
- setRawDateNumber(p, sqlite3_value_double(argv[0]));
- }else{
- z = sqlite3_value_text(argv[0]);
- if( !z || parseDateOrTime(context, (char*)z, p) ){
- return 1;
- }
- }
- for(i=1; iisError || !validJulianDay(p->iJD) ) 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;
- if( isDate(context, argc, argv, &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;
- if( isDate(context, argc, argv, &x)==0 ){
- char zBuf[100];
- computeYMD_HMS(&x);
- sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
- x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
- sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
- }
-}
-
-/*
-** time( TIMESTRING, MOD, MOD, ...)
-**
-** Return HH:MM:SS
-*/
-static void timeFunc(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
-){
- DateTime x;
- if( isDate(context, argc, argv, &x)==0 ){
- char zBuf[100];
- computeHMS(&x);
- sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
- sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
- }
-}
-
-/*
-** date( TIMESTRING, MOD, MOD, ...)
-**
-** Return YYYY-MM-DD
-*/
-static void dateFunc(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
-){
- DateTime x;
- if( isDate(context, argc, argv, &x)==0 ){
- char zBuf[100];
- computeYMD(&x);
- sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
- sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
- }
-}
-
-/*
-** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
-**
-** Return a string described by FORMAT. Conversions as follows:
-**
-** %d day of month
-** %f ** fractional seconds SS.SSS
-** %H hour 00-24
-** %j day of year 000-366
-** %J ** julian day number
-** %m month 01-12
-** %M minute 00-59
-** %s seconds since 1970-01-01
-** %S seconds 00-59
-** %w day of week 0-6 sunday==0
-** %W week of year 00-53
-** %Y year 0000-9999
-** %% %
-*/
-static void strftimeFunc(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
-){
- DateTime x;
- u64 n;
- size_t i,j;
- char *z;
- sqlite3 *db;
- const char *zFmt;
- char zBuf[100];
- if( argc==0 ) return;
- zFmt = (const char*)sqlite3_value_text(argv[0]);
- if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
- db = sqlite3_context_db_handle(context);
- for(i=0, n=1; zFmt[i]; i++, n++){
- if( zFmt[i]=='%' ){
- switch( zFmt[i+1] ){
- case 'd':
- case 'H':
- case 'm':
- case 'M':
- case 'S':
- case 'W':
- n++;
- /* 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==sizeof(zBuf)-1 );
- testcase( n==sizeof(zBuf) );
- testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
- testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
- if( n(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
- sqlite3_result_error_toobig(context);
- return;
- }else{
- z = sqlite3DbMallocRawNN(db, (int)n);
- if( z==0 ){
- sqlite3_result_error_nomem(context);
- return;
- }
- }
- computeJD(&x);
- computeYMD_HMS(&x);
- for(i=j=0; zFmt[i]; i++){
- if( zFmt[i]!='%' ){
- z[j++] = zFmt[i];
- }else{
- i++;
- switch( zFmt[i] ){
- case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
- case 'f': {
- double s = x.s;
- if( s>59.999 ) s = 59.999;
- sqlite3_snprintf(7, &z[j],"%06.3f", s);
- j += sqlite3Strlen30(&z[j]);
- break;
- }
- case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
- case 'W': /* Fall thru */
- case 'j': {
- int nDay; /* Number of days since 1st day of year */
- DateTime y = x;
- 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, &z[j],"%02d",(nDay+7-wd)/7);
- j += 2;
- }else{
- sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
- j += 3;
- }
- break;
- }
- case 'J': {
- sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
- j+=sqlite3Strlen30(&z[j]);
- break;
- }
- case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
- case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
- case 's': {
- sqlite3_snprintf(30,&z[j],"%lld",
- (i64)(x.iJD/1000 - 21086676*(i64)10000));
- j += sqlite3Strlen30(&z[j]);
- break;
- }
- case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
- case 'w': {
- z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
- break;
- }
- case 'Y': {
- sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
- break;
- }
- default: z[j++] = '%'; break;
- }
- }
- }
- z[j] = 0;
- sqlite3_result_text(context, z, -1,
- z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
-}
-
-/*
-** current_time()
-**
-** This function returns the same value as time('now').
-*/
-static void ctimeFunc(
- sqlite3_context *context,
- int NotUsed,
- sqlite3_value **NotUsed2
-){
- UNUSED_PARAMETER2(NotUsed, NotUsed2);
- timeFunc(context, 0, 0);
-}
-
-/*
-** 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, 0);
-}
-
-/*
-** 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, 0);
-}
-#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
-
-#ifdef SQLITE_OMIT_DATETIME_FUNCS
-/*
-** If the library is compiled to omit the full-scale date and time
-** handling (to get a smaller binary), the following minimal version
-** of the functions current_time(), current_date() and current_timestamp()
-** are included instead. This is to support column declarations that
-** include "DEFAULT CURRENT_TIME" etc.
-**
-** This function uses the C-library functions time(), gmtime()
-** and strftime(). The format string to pass to strftime() is supplied
-** as the user-data for the function.
-*/
-static void currentTimeFunc(
- sqlite3_context *context,
- int argc,
- sqlite3_value **argv
-){
- time_t t;
- char *zFormat = (char *)sqlite3_user_data(context);
- sqlite3_int64 iT;
- struct tm *pTm;
- struct tm sNow;
- char zBuf[20];
-
- UNUSED_PARAMETER(argc);
- UNUSED_PARAMETER(argv);
-
- iT = sqlite3StmtCurrentTime(context);
- if( iT<=0 ) return;
- t = iT/1000 - 10000*(sqlite3_int64)21086676;
-#if HAVE_GMTIME_R
- pTm = gmtime_r(&t, &sNow);
-#else
- sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
- pTm = gmtime(&t);
- if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
- sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
-#endif
- if( pTm ){
- strftime(zBuf, 20, zFormat, &sNow);
- sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
- }
-}
-#endif
-
-/*
-** This function registered all of the above C functions as SQL
-** functions. This should be the only routine in this file with
-** external linkage.
-*/
-SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
- static FuncDef aDateTimeFuncs[] = {
-#ifndef SQLITE_OMIT_DATETIME_FUNCS
- PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
- PURE_DATE(date, -1, 0, 0, dateFunc ),
- PURE_DATE(time, -1, 0, 0, timeFunc ),
- PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
- PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
- DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
- DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
- DFUNCTION(current_date, 0, 0, 0, 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
- };
- sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
-}
-
-/************** End of date.c ************************************************/
-/************** Begin file os.c **********************************************/
-/*
-** 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.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** 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 defined(SQLITE_TEST)
-SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
-SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
-SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
-SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
-SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
-SQLITE_API int sqlite3_diskfull_pending = 0;
-SQLITE_API int sqlite3_diskfull = 0;
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, also keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API int sqlite3_open_file_count = 0;
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** 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:
-**
-** sqlite3OsRead()
-** sqlite3OsWrite()
-** sqlite3OsSync()
-** sqlite3OsFileSize()
-** sqlite3OsLock()
-** sqlite3OsCheckReservedLock()
-** sqlite3OsFileControl()
-** sqlite3OsShmMap()
-** sqlite3OsOpen()
-** sqlite3OsDelete()
-** sqlite3OsAccess()
-** sqlite3OsFullPathname()
-**
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
- #define DO_OS_MALLOC_TEST(x) \
- if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
- void *pTstAlloc = sqlite3Malloc(10); \
- if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
- sqlite3_free(pTstAlloc); \
- }
-#else
- #define DO_OS_MALLOC_TEST(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.
-*/
-SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
- if( pId->pMethods ){
- pId->pMethods->xClose(pId);
- pId->pMethods = 0;
- }
-}
-SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xRead(id, pBuf, amt, offset);
-}
-SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xWrite(id, pBuf, amt, offset);
-}
-SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
- return id->pMethods->xTruncate(id, size);
-}
-SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
- DO_OS_MALLOC_TEST(id);
- return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
-}
-SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xFileSize(id, pSize);
-}
-SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xLock(id, lockType);
-}
-SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
- return id->pMethods->xUnlock(id, lockType);
-}
-SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xCheckReservedLock(id, pResOut);
-}
-
-/*
-** Use sqlite3OsFileControl() when we are doing something that might fail
-** and we need to know about the failures. Use sqlite3OsFileControlHint()
-** when simply tossing information over the wall to the VFS and we do not
-** really care if the VFS receives and understands the information since it
-** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
-** routine has no return value since the return value would be meaningless.
-*/
-SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
- if( id->pMethods==0 ) return SQLITE_NOTFOUND;
-#ifdef SQLITE_TEST
- if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
- && op!=SQLITE_FCNTL_LOCK_TIMEOUT
- ){
- /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
- ** is using a regular VFS, it is called after the corresponding
- ** transaction has been committed. Injecting a fault at this point
- ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
- ** but the transaction is committed anyway.
- **
- ** The core must call OsFileControl() though, not OsFileControlHint(),
- ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
- ** means the commit really has failed and an error should be returned
- ** to the user. */
- DO_OS_MALLOC_TEST(id);
- }
-#endif
- return id->pMethods->xFileControl(id, op, pArg);
-}
-SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
- if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
-}
-
-SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
- int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
- return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
-}
-SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
- return id->pMethods->xDeviceCharacteristics(id);
-}
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
- return id->pMethods->xShmLock(id, offset, n, flags);
-}
-SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
- id->pMethods->xShmBarrier(id);
-}
-SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
- return id->pMethods->xShmUnmap(id, deleteFlag);
-}
-SQLITE_PRIVATE int sqlite3OsShmMap(
- sqlite3_file *id, /* Database file handle */
- int iPage,
- int pgsz,
- int bExtend, /* True to extend file if necessary */
- void volatile **pp /* OUT: Pointer to mapping */
-){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
-}
-#endif /* SQLITE_OMIT_WAL */
-
-#if SQLITE_MAX_MMAP_SIZE>0
-/* The real implementation of xFetch and xUnfetch */
-SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
- DO_OS_MALLOC_TEST(id);
- return id->pMethods->xFetch(id, iOff, iAmt, pp);
-}
-SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
- return id->pMethods->xUnfetch(id, iOff, p);
-}
-#else
-/* No-op stubs to use when memory-mapped I/O is disabled */
-SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
- *pp = 0;
- return SQLITE_OK;
-}
-SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
- return SQLITE_OK;
-}
-#endif
-
-/*
-** The next group of routines are convenience wrappers around the
-** VFS methods.
-*/
-SQLITE_PRIVATE int sqlite3OsOpen(
- sqlite3_vfs *pVfs,
- const char *zPath,
- sqlite3_file *pFile,
- int flags,
- int *pFlagsOut
-){
- int rc;
- DO_OS_MALLOC_TEST(0);
- /* 0x87f7f 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 & 0x87f7f, pFlagsOut);
- assert( rc==SQLITE_OK || pFile->pMethods==0 );
- return rc;
-}
-SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
- DO_OS_MALLOC_TEST(0);
- assert( dirSync==0 || dirSync==1 );
- return pVfs->xDelete(pVfs, zPath, dirSync);
-}
-SQLITE_PRIVATE int sqlite3OsAccess(
- sqlite3_vfs *pVfs,
- const char *zPath,
- int flags,
- int *pResOut
-){
- DO_OS_MALLOC_TEST(0);
- return pVfs->xAccess(pVfs, zPath, flags, pResOut);
-}
-SQLITE_PRIVATE int sqlite3OsFullPathname(
- sqlite3_vfs *pVfs,
- const char *zPath,
- int nPathOut,
- char *zPathOut
-){
- DO_OS_MALLOC_TEST(0);
- zPathOut[0] = 0;
- return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
-}
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
- return pVfs->xDlOpen(pVfs, zPath);
-}
-SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
- pVfs->xDlError(pVfs, nByte, zBufOut);
-}
-SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
- return pVfs->xDlSym(pVfs, pHdle, zSym);
-}
-SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
- pVfs->xDlClose(pVfs, pHandle);
-}
-#endif /* SQLITE_OMIT_LOAD_EXTENSION */
-SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
- return pVfs->xRandomness(pVfs, nByte, zBufOut);
-}
-SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
- return pVfs->xSleep(pVfs, nMicro);
-}
-SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
- return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
-}
-SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, 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 ){
- rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
- }else{
- double r;
- rc = pVfs->xCurrentTime(pVfs, &r);
- *pTimeOut = (sqlite3_int64)(r*86400000.0);
- }
- return rc;
-}
-
-SQLITE_PRIVATE int sqlite3OsOpenMalloc(
- sqlite3_vfs *pVfs,
- const char *zFile,
- sqlite3_file **ppFile,
- int flags,
- int *pOutFlags
-){
- int rc;
- sqlite3_file *pFile;
- pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
- if( pFile ){
- rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
- if( rc!=SQLITE_OK ){
- sqlite3_free(pFile);
- }else{
- *ppFile = pFile;
- }
- }else{
- rc = SQLITE_NOMEM_BKPT;
- }
- return rc;
-}
-SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
- assert( pFile );
- sqlite3OsClose(pFile);
- sqlite3_free(pFile);
-}
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE int sqlite3OsInit(void){
- void *p = sqlite3_malloc(10);
- if( p==0 ) return SQLITE_NOMEM_BKPT;
- sqlite3_free(p);
- return sqlite3_os_init();
-}
-
-/*
-** The list of all registered VFS implementations.
-*/
-static sqlite3_vfs * SQLITE_WSD vfsList = 0;
-#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
-
-/*
-** Locate a VFS by name. If no name is given, simply return the
-** first VFS on the list.
-*/
-SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
- sqlite3_vfs *pVfs = 0;
-#if SQLITE_THREADSAFE
- sqlite3_mutex *mutex;
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- int rc = sqlite3_initialize();
- if( rc ) return 0;
-#endif
-#if SQLITE_THREADSAFE
- mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
-#endif
- sqlite3_mutex_enter(mutex);
- for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
- if( zVfs==0 ) break;
- if( strcmp(zVfs, pVfs->zName)==0 ) break;
- }
- sqlite3_mutex_leave(mutex);
- return pVfs;
-}
-
-/*
-** Unlink a VFS from the linked list
-*/
-static void vfsUnlink(sqlite3_vfs *pVfs){
- assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
- if( pVfs==0 ){
- /* No-op */
- }else if( vfsList==pVfs ){
- vfsList = pVfs->pNext;
- }else if( vfsList ){
- sqlite3_vfs *p = vfsList;
- while( p->pNext && 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.
-*/
-SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
- MUTEX_LOGIC(sqlite3_mutex *mutex;)
-#ifndef SQLITE_OMIT_AUTOINIT
- int rc = sqlite3_initialize();
- if( rc ) return rc;
-#endif
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
-#endif
-
- MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
- sqlite3_mutex_enter(mutex);
- vfsUnlink(pVfs);
- if( makeDflt || vfsList==0 ){
- pVfs->pNext = vfsList;
- vfsList = pVfs;
- }else{
- pVfs->pNext = vfsList->pNext;
- vfsList->pNext = pVfs;
- }
- assert(vfsList);
- sqlite3_mutex_leave(mutex);
- return SQLITE_OK;
-}
-
-/*
-** Unregister a VFS so that it is no longer accessible.
-*/
-SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
- MUTEX_LOGIC(sqlite3_mutex *mutex;)
-#ifndef SQLITE_OMIT_AUTOINIT
- int rc = sqlite3_initialize();
- if( rc ) return rc;
-#endif
- MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
- sqlite3_mutex_enter(mutex);
- vfsUnlink(pVfs);
- sqlite3_mutex_leave(mutex);
- return SQLITE_OK;
-}
-
-/************** End of os.c **************************************************/
-/************** Begin file fault.c *******************************************/
-/*
-** 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.
-*/
-
-/* #include "sqliteInt.h" */
-
-#ifndef SQLITE_UNTESTABLE
-
-/*
-** Global variables.
-*/
-typedef struct BenignMallocHooks BenignMallocHooks;
-static SQLITE_WSD struct BenignMallocHooks {
- void (*xBenignBegin)(void);
- void (*xBenignEnd)(void);
-} sqlite3Hooks = { 0, 0 };
-
-/* 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.
-*/
-#ifdef SQLITE_OMIT_WSD
-# define wsdHooksInit \
- BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
-# define wsdHooks x[0]
-#else
-# define wsdHooksInit
-# define wsdHooks sqlite3Hooks
-#endif
-
-
-/*
-** Register hooks to call when sqlite3BeginBenignMalloc() and
-** sqlite3EndBenignMalloc() are called, respectively.
-*/
-SQLITE_PRIVATE void sqlite3BenignMallocHooks(
- void (*xBenignBegin)(void),
- 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.
-*/
-SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
- wsdHooksInit;
- if( wsdHooks.xBenignBegin ){
- wsdHooks.xBenignBegin();
- }
-}
-SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
- wsdHooksInit;
- if( wsdHooks.xBenignEnd ){
- wsdHooks.xBenignEnd();
- }
-}
-
-#endif /* #ifndef SQLITE_UNTESTABLE */
-
-/************** End of fault.c ***********************************************/
-/************** Begin file mem0.c ********************************************/
-/*
-** 2008 October 28
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file contains a no-op memory allocation drivers for use when
-** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
-** here always fail. SQLite will not operate with these drivers. These
-** are merely placeholders. Real drivers must be substituted using
-** sqlite3_config() before SQLite will operate.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** This version of the memory allocator is the default. It is
-** used when no other memory allocator is specified using compile-time
-** macros.
-*/
-#ifdef SQLITE_ZERO_MALLOC
-
-/*
-** No-op versions of all memory allocation routines
-*/
-static void *sqlite3MemMalloc(int nByte){ return 0; }
-static void sqlite3MemFree(void *pPrior){ return; }
-static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
-static int sqlite3MemSize(void *pPrior){ return 0; }
-static int sqlite3MemRoundup(int n){ return n; }
-static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
-static void sqlite3MemShutdown(void *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.
-*/
-SQLITE_PRIVATE void sqlite3MemSetDefault(void){
- static const sqlite3_mem_methods defaultMethods = {
- sqlite3MemMalloc,
- sqlite3MemFree,
- sqlite3MemRealloc,
- sqlite3MemSize,
- sqlite3MemRoundup,
- sqlite3MemInit,
- sqlite3MemShutdown,
- 0
- };
- sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
-}
-
-#endif /* SQLITE_ZERO_MALLOC */
-
-/************** End of mem0.c ************************************************/
-/************** Begin file mem1.c ********************************************/
-/*
-** 2007 August 14
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file contains low-level memory allocation drivers for when
-** SQLite will use the standard C-library malloc/realloc/free interface
-** to obtain the memory it needs.
-**
-** This file contains implementations of the low-level memory allocation
-** routines specified in the sqlite3_mem_methods object. The content of
-** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
-** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
-** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
-** default configuration is to use memory allocation routines in this
-** file.
-**
-** C-preprocessor macro summary:
-**
-** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
-** the malloc_usable_size() interface exists
-** on the target platform. Or, this symbol
-** can be set manually, if desired.
-** If an equivalent interface exists by
-** a different name, using a separate -D
-** option to rename it.
-**
-** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
-** memory allocator. Set this symbol to enable
-** building on older macs.
-**
-** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
-** _msize() on windows systems. This might
-** be necessary when compiling for Delphi,
-** for example.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** This version of the memory allocator is the default. It is
-** used when no other memory allocator is specified using compile-time
-** macros.
-*/
-#ifdef SQLITE_SYSTEM_MALLOC
-#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
-
-/*
-** Use the zone allocator available on apple products unless the
-** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
-*/
-#include
-#include
-#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
-#include
-#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
-static malloc_zone_t* _sqliteZone_;
-#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
-#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
-#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
-#define SQLITE_MALLOCSIZE(x) \
- (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
-
-#else /* if not __APPLE__ */
-
-/*
-** Use standard C library malloc and free on non-Apple systems.
-** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
-*/
-#define SQLITE_MALLOC(x) malloc(x)
-#define SQLITE_FREE(x) free(x)
-#define SQLITE_REALLOC(x,y) realloc((x),(y))
-
-/*
-** The malloc.h header file is needed for malloc_usable_size() function
-** on some systems (e.g. Linux).
-*/
-#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
-# define SQLITE_USE_MALLOC_H 1
-# define SQLITE_USE_MALLOC_USABLE_SIZE 1
-/*
-** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
-** use of _msize() is automatic, but can be disabled by compiling with
-** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
-** the malloc.h header file.
-*/
-#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
-# define SQLITE_USE_MALLOC_H
-# define SQLITE_USE_MSIZE
-#endif
-
-/*
-** Include the malloc.h header file, if necessary. Also set define macro
-** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
-** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
-** The memory size function can always be overridden manually by defining
-** the macro SQLITE_MALLOCSIZE to the desired function name.
-*/
-#if defined(SQLITE_USE_MALLOC_H)
-# include
-# if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
-# if !defined(SQLITE_MALLOCSIZE)
-# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
-# endif
-# elif defined(SQLITE_USE_MSIZE)
-# if !defined(SQLITE_MALLOCSIZE)
-# define SQLITE_MALLOCSIZE _msize
-# endif
-# endif
-#endif /* defined(SQLITE_USE_MALLOC_H) */
-
-#endif /* __APPLE__ or not __APPLE__ */
-
-/*
-** Like malloc(), but remember the size of the allocation
-** so that we can find it later using sqlite3MemSize().
-**
-** For this low-level routine, we are guaranteed that nByte>0 because
-** cases of nByte<=0 will be intercepted and dealt with by higher level
-** routines.
-*/
-static void *sqlite3MemMalloc(int nByte){
-#ifdef SQLITE_MALLOCSIZE
- void *p;
- testcase( ROUND8(nByte)==nByte );
- p = SQLITE_MALLOC( nByte );
- if( p==0 ){
- testcase( sqlite3GlobalConfig.xLog!=0 );
- sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
- }
- return p;
-#else
- sqlite3_int64 *p;
- assert( nByte>0 );
- testcase( ROUND8(nByte)!=nByte );
- p = SQLITE_MALLOC( nByte+8 );
- if( p ){
- p[0] = nByte;
- p++;
- }else{
- testcase( sqlite3GlobalConfig.xLog!=0 );
- sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
- }
- return (void *)p;
-#endif
-}
-
-/*
-** Like free() but works for allocations obtained from sqlite3MemMalloc()
-** or sqlite3MemRealloc().
-**
-** For this low-level routine, we already know that pPrior!=0 since
-** cases where pPrior==0 will have been intecepted and dealt with
-** by higher-level routines.
-*/
-static void sqlite3MemFree(void *pPrior){
-#ifdef SQLITE_MALLOCSIZE
- SQLITE_FREE(pPrior);
-#else
- sqlite3_int64 *p = (sqlite3_int64*)pPrior;
- assert( pPrior!=0 );
- p--;
- SQLITE_FREE(p);
-#endif
-}
-
-/*
-** Report the allocated size of a prior return from xMalloc()
-** or xRealloc().
-*/
-static int sqlite3MemSize(void *pPrior){
-#ifdef SQLITE_MALLOCSIZE
- assert( pPrior!=0 );
- return (int)SQLITE_MALLOCSIZE(pPrior);
-#else
- sqlite3_int64 *p;
- assert( pPrior!=0 );
- p = (sqlite3_int64*)pPrior;
- p--;
- return (int)p[0];
-#endif
-}
-
-/*
-** 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 because
-** cases where nByte<=0 will have been intercepted by higher-level
-** routines and redirected to xFree.
-*/
-static void *sqlite3MemRealloc(void *pPrior, int nByte){
-#ifdef SQLITE_MALLOCSIZE
- void *p = SQLITE_REALLOC(pPrior, nByte);
- if( p==0 ){
- testcase( sqlite3GlobalConfig.xLog!=0 );
- sqlite3_log(SQLITE_NOMEM,
- "failed memory resize %u to %u bytes",
- SQLITE_MALLOCSIZE(pPrior), nByte);
- }
- return p;
-#else
- sqlite3_int64 *p = (sqlite3_int64*)pPrior;
- assert( pPrior!=0 && nByte>0 );
- assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
- p--;
- p = SQLITE_REALLOC(p, nByte+8 );
- if( p ){
- p[0] = nByte;
- p++;
- }else{
- testcase( sqlite3GlobalConfig.xLog!=0 );
- sqlite3_log(SQLITE_NOMEM,
- "failed memory resize %u to %u bytes",
- sqlite3MemSize(pPrior), nByte);
- }
- return (void*)p;
-#endif
-}
-
-/*
-** Round up a request size to the next valid allocation size.
-*/
-static int sqlite3MemRoundup(int n){
- return ROUND8(n);
-}
-
-/*
-** Initialize this module.
-*/
-static int sqlite3MemInit(void *NotUsed){
-#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
- int cpuCount;
- size_t len;
- if( _sqliteZone_ ){
- return SQLITE_OK;
- }
- len = sizeof(cpuCount);
- /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
- sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
- if( cpuCount>1 ){
- /* defer MT decisions to system malloc */
- _sqliteZone_ = malloc_default_zone();
- }else{
- /* only 1 core, use our own zone to contention over global locks,
- ** e.g. we have our own dedicated locks */
- _sqliteZone_ = malloc_create_zone(4096, 0);
- malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
- }
-#endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
- UNUSED_PARAMETER(NotUsed);
- return SQLITE_OK;
-}
-
-/*
-** Deinitialize this module.
-*/
-static void sqlite3MemShutdown(void *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.
-*/
-SQLITE_PRIVATE void sqlite3MemSetDefault(void){
- static const sqlite3_mem_methods defaultMethods = {
- sqlite3MemMalloc,
- sqlite3MemFree,
- sqlite3MemRealloc,
- sqlite3MemSize,
- sqlite3MemRoundup,
- sqlite3MemInit,
- sqlite3MemShutdown,
- 0
- };
- sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
-}
-
-#endif /* SQLITE_SYSTEM_MALLOC */
-
-/************** End of mem1.c ************************************************/
-/************** Begin file mem2.c ********************************************/
-/*
-** 2007 August 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 low-level memory allocation drivers for when
-** SQLite will use the standard C-library malloc/realloc/free interface
-** to obtain the memory it needs while adding lots of additional debugging
-** information to each allocation in order to help detect and fix memory
-** leaks and memory usage errors.
-**
-** This file contains implementations of the low-level memory allocation
-** routines specified in the sqlite3_mem_methods object.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** This version of the memory allocator is used only if the
-** SQLITE_MEMDEBUG macro is defined
-*/
-#ifdef SQLITE_MEMDEBUG
-
-/*
-** The backtrace functionality is only available with GLIBC
-*/
-#ifdef __GLIBC__
- extern int backtrace(void**,int);
- extern void backtrace_symbols_fd(void*const*,int,int);
-#else
-# define backtrace(A,B) 1
-# define backtrace_symbols_fd(A,B,C)
-#endif
-/* #include */
-
-/*
-** Each memory allocation looks like this:
-**
-** ------------------------------------------------------------------------
-** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
-** ------------------------------------------------------------------------
-**
-** The application code sees only a pointer to the allocation. We have
-** to back up from the allocation pointer to find the MemBlockHdr. The
-** MemBlockHdr tells us the size of the allocation and the number of
-** backtrace pointers. There is also a guard word at the end of the
-** MemBlockHdr.
-*/
-struct MemBlockHdr {
- i64 iSize; /* Size of this allocation */
- struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
- char nBacktrace; /* Number of backtraces on this alloc */
- char nBacktraceSlots; /* Available backtrace slots */
- u8 nTitle; /* Bytes of title; includes '\0' */
- u8 eType; /* Allocation type code */
- int iForeGuard; /* Guard word for sanity */
-};
-
-/*
-** Guard words
-*/
-#define FOREGUARD 0x80F5E153
-#define REARGUARD 0xE4676B53
-
-/*
-** Number of malloc size increments to track.
-*/
-#define NCSIZE 1000
-
-/*
-** All of the static variables used by this module are collected
-** into a single structure named "mem". This is to keep the
-** static variables organized and to reduce namespace pollution
-** when this module is combined with other in the amalgamation.
-*/
-static struct {
-
- /*
- ** Mutex to control access to the memory allocation subsystem.
- */
- sqlite3_mutex *mutex;
-
- /*
- ** Head and tail of a linked list of all outstanding allocations
- */
- struct MemBlockHdr *pFirst;
- struct MemBlockHdr *pLast;
-
- /*
- ** The number of levels of backtrace to save in new allocations.
- */
- int nBacktrace;
- void (*xBacktrace)(int, int, void **);
-
- /*
- ** Title text to insert in front of each block
- */
- int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
- char zTitle[100]; /* The title text */
-
- /*
- ** sqlite3MallocDisallow() increments the following counter.
- ** sqlite3MallocAllow() decrements it.
- */
- int disallow; /* Do not allow memory allocation */
-
- /*
- ** Gather statistics on the sizes of memory allocations.
- ** nAlloc[i] is the number of allocation attempts of i*8
- ** bytes. i==NCSIZE is the number of allocation attempts for
- ** sizes more than NCSIZE*8 bytes.
- */
- int nAlloc[NCSIZE]; /* Total number of allocations */
- int nCurrent[NCSIZE]; /* Current number of allocations */
- int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
-
-} mem;
-
-
-/*
-** Adjust memory usage statistics
-*/
-static void adjustStats(int iSize, int increment){
- int i = ROUND8(iSize)/8;
- if( i>NCSIZE-1 ){
- i = NCSIZE - 1;
- }
- if( increment>0 ){
- mem.nAlloc[i]++;
- mem.nCurrent[i]++;
- if( mem.nCurrent[i]>mem.mxCurrent[i] ){
- mem.mxCurrent[i] = mem.nCurrent[i];
- }
- }else{
- mem.nCurrent[i]--;
- assert( mem.nCurrent[i]>=0 );
- }
-}
-
-/*
-** Given an allocation, find the MemBlockHdr for that allocation.
-**
-** This routine checks the guards at either end of the allocation and
-** if they are incorrect it asserts.
-*/
-static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
- struct MemBlockHdr *p;
- int *pInt;
- u8 *pU8;
- int nReserve;
-
- p = (struct MemBlockHdr*)pAllocation;
- p--;
- assert( p->iForeGuard==(int)FOREGUARD );
- nReserve = ROUND8(p->iSize);
- pInt = (int*)pAllocation;
- pU8 = (u8*)pAllocation;
- assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
- /* This checks any of the "extra" bytes allocated due
- ** to rounding up to an 8 byte boundary to ensure
- ** they haven't been overwritten.
- */
- while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
- return p;
-}
-
-/*
-** Return the number of bytes currently allocated at address p.
-*/
-static int sqlite3MemSize(void *p){
- struct MemBlockHdr *pHdr;
- if( !p ){
- return 0;
- }
- pHdr = sqlite3MemsysGetHeader(p);
- return (int)pHdr->iSize;
-}
-
-/*
-** Initialize the memory allocation subsystem.
-*/
-static int sqlite3MemInit(void *NotUsed){
- UNUSED_PARAMETER(NotUsed);
- assert( (sizeof(struct MemBlockHdr)&7) == 0 );
- 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. */
- mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
- }
- return SQLITE_OK;
-}
-
-/*
-** Deinitialize the memory allocation subsystem.
-*/
-static void sqlite3MemShutdown(void *NotUsed){
- UNUSED_PARAMETER(NotUsed);
- mem.mutex = 0;
-}
-
-/*
-** Round up a request size to the next valid allocation size.
-*/
-static int sqlite3MemRoundup(int n){
- return ROUND8(n);
-}
-
-/*
-** Fill a buffer with pseudo-random bytes. This is used to preset
-** the content of a new memory allocation to unpredictable values and
-** to clear the content of a freed allocation to unpredictable values.
-*/
-static void randomFill(char *pBuf, int nByte){
- unsigned int x, y, r;
- x = SQLITE_PTR_TO_INT(pBuf);
- y = nByte | 1;
- while( nByte >= 4 ){
- x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
- y = y*1103515245 + 12345;
- r = x ^ y;
- *(int*)pBuf = r;
- pBuf += 4;
- nByte -= 4;
- }
- while( nByte-- > 0 ){
- x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
- y = y*1103515245 + 12345;
- r = x ^ y;
- *(pBuf++) = r & 0xff;
- }
-}
-
-/*
-** Allocate nByte bytes of memory.
-*/
-static void *sqlite3MemMalloc(int nByte){
- struct MemBlockHdr *pHdr;
- void **pBt;
- char *z;
- int *pInt;
- void *p = 0;
- int totalSize;
- int nReserve;
- sqlite3_mutex_enter(mem.mutex);
- assert( mem.disallow==0 );
- nReserve = ROUND8(nByte);
- totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
- mem.nBacktrace*sizeof(void*) + mem.nTitle;
- p = malloc(totalSize);
- if( p ){
- z = p;
- pBt = (void**)&z[mem.nTitle];
- pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
- pHdr->pNext = 0;
- pHdr->pPrev = mem.pLast;
- if( mem.pLast ){
- mem.pLast->pNext = pHdr;
- }else{
- mem.pFirst = pHdr;
- }
- mem.pLast = pHdr;
- pHdr->iForeGuard = FOREGUARD;
- pHdr->eType = MEMTYPE_HEAP;
- pHdr->nBacktraceSlots = mem.nBacktrace;
- pHdr->nTitle = mem.nTitle;
- if( mem.nBacktrace ){
- void *aAddr[40];
- pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
- memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
- assert(pBt[0]);
- if( mem.xBacktrace ){
- mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
- }
- }else{
- pHdr->nBacktrace = 0;
- }
- if( mem.nTitle ){
- memcpy(z, mem.zTitle, mem.nTitle);
- }
- pHdr->iSize = nByte;
- adjustStats(nByte, +1);
- pInt = (int*)&pHdr[1];
- pInt[nReserve/sizeof(int)] = REARGUARD;
- randomFill((char*)pInt, nByte);
- memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
- p = (void*)pInt;
- }
- sqlite3_mutex_leave(mem.mutex);
- return p;
-}
-
-/*
-** Free memory.
-*/
-static void sqlite3MemFree(void *pPrior){
- struct MemBlockHdr *pHdr;
- void **pBt;
- char *z;
- assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
- || mem.mutex!=0 );
- pHdr = sqlite3MemsysGetHeader(pPrior);
- pBt = (void**)pHdr;
- pBt -= pHdr->nBacktraceSlots;
- sqlite3_mutex_enter(mem.mutex);
- if( pHdr->pPrev ){
- assert( pHdr->pPrev->pNext==pHdr );
- pHdr->pPrev->pNext = pHdr->pNext;
- }else{
- assert( mem.pFirst==pHdr );
- mem.pFirst = pHdr->pNext;
- }
- if( pHdr->pNext ){
- assert( pHdr->pNext->pPrev==pHdr );
- pHdr->pNext->pPrev = pHdr->pPrev;
- }else{
- assert( mem.pLast==pHdr );
- mem.pLast = pHdr->pPrev;
- }
- z = (char*)pBt;
- z -= pHdr->nTitle;
- adjustStats((int)pHdr->iSize, -1);
- randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
- (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
- free(z);
- sqlite3_mutex_leave(mem.mutex);
-}
-
-/*
-** Change the size of an existing memory allocation.
-**
-** For this debugging implementation, we *always* make a copy of the
-** allocation into a new place in memory. In this way, if the
-** higher level code is using pointer to the old allocation, it is
-** much more likely to break and we are much more liking to find
-** the error.
-*/
-static void *sqlite3MemRealloc(void *pPrior, int nByte){
- struct MemBlockHdr *pOldHdr;
- void *pNew;
- assert( mem.disallow==0 );
- assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
- pOldHdr = sqlite3MemsysGetHeader(pPrior);
- pNew = sqlite3MemMalloc(nByte);
- if( pNew ){
- memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize));
- if( nByte>pOldHdr->iSize ){
- randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
- }
- sqlite3MemFree(pPrior);
- }
- return pNew;
-}
-
-/*
-** Populate the low-level memory allocation function pointers in
-** sqlite3GlobalConfig.m with pointers to the routines in this file.
-*/
-SQLITE_PRIVATE void sqlite3MemSetDefault(void){
- static const sqlite3_mem_methods defaultMethods = {
- sqlite3MemMalloc,
- sqlite3MemFree,
- sqlite3MemRealloc,
- sqlite3MemSize,
- sqlite3MemRoundup,
- sqlite3MemInit,
- sqlite3MemShutdown,
- 0
- };
- sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
-}
-
-/*
-** Set the "type" of an allocation.
-*/
-SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
- if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
- struct MemBlockHdr *pHdr;
- pHdr = sqlite3MemsysGetHeader(p);
- assert( pHdr->iForeGuard==FOREGUARD );
- pHdr->eType = eType;
- }
-}
-
-/*
-** Return TRUE if the mask of type in eType matches the type of the
-** allocation p. Also return true if p==NULL.
-**
-** This routine is designed for use within an assert() statement, to
-** verify the type of an allocation. For example:
-**
-** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
-*/
-SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
- int rc = 1;
- if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
- struct MemBlockHdr *pHdr;
- pHdr = sqlite3MemsysGetHeader(p);
- assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
- if( (pHdr->eType&eType)==0 ){
- rc = 0;
- }
- }
- return rc;
-}
-
-/*
-** Return TRUE if the mask of type in eType matches no bits of the type of the
-** allocation p. Also return true if p==NULL.
-**
-** This routine is designed for use within an assert() statement, to
-** verify the type of an allocation. For example:
-**
-** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
-*/
-SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
- int rc = 1;
- if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
- struct MemBlockHdr *pHdr;
- pHdr = sqlite3MemsysGetHeader(p);
- assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
- if( (pHdr->eType&eType)!=0 ){
- rc = 0;
- }
- }
- return rc;
-}
-
-/*
-** Set the number of backtrace levels kept for each allocation.
-** A value of zero turns off backtracing. The number is always rounded
-** up to a multiple of 2.
-*/
-SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
- if( depth<0 ){ depth = 0; }
- if( depth>20 ){ depth = 20; }
- depth = (depth+1)&0xfe;
- mem.nBacktrace = depth;
-}
-
-SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
- mem.xBacktrace = xBacktrace;
-}
-
-/*
-** Set the title string for subsequent allocations.
-*/
-SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
- unsigned int n = sqlite3Strlen30(zTitle) + 1;
- sqlite3_mutex_enter(mem.mutex);
- if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
- memcpy(mem.zTitle, zTitle, n);
- mem.zTitle[n] = 0;
- mem.nTitle = ROUND8(n);
- sqlite3_mutex_leave(mem.mutex);
-}
-
-SQLITE_PRIVATE void sqlite3MemdebugSync(){
- struct MemBlockHdr *pHdr;
- for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
- void **pBt = (void**)pHdr;
- pBt -= pHdr->nBacktraceSlots;
- mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
- }
-}
-
-/*
-** Open the file indicated and write a log of all unfreed memory
-** allocations into that log.
-*/
-SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
- FILE *out;
- struct MemBlockHdr *pHdr;
- void **pBt;
- int i;
- out = fopen(zFilename, "w");
- if( out==0 ){
- fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
- zFilename);
- return;
- }
- for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
- char *z = (char*)pHdr;
- z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
- fprintf(out, "**** %lld bytes at %p from %s ****\n",
- pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
- if( pHdr->nBacktrace ){
- fflush(out);
- pBt = (void**)pHdr;
- pBt -= pHdr->nBacktraceSlots;
- backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
- fprintf(out, "\n");
- }
- }
- fprintf(out, "COUNTS:\n");
- for(i=0; i=1 );
- size = mem3.aPool[i-1].u.hdr.size4x/4;
- assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
- assert( size>=2 );
- if( size <= MX_SMALL ){
- memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
- }else{
- hash = size % N_HASH;
- memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
- }
-}
-
-/*
-** Link the chunk at mem3.aPool[i] so that is on the list rooted
-** at *pRoot.
-*/
-static void memsys3LinkIntoList(u32 i, u32 *pRoot){
- assert( sqlite3_mutex_held(mem3.mutex) );
- mem3.aPool[i].u.list.next = *pRoot;
- mem3.aPool[i].u.list.prev = 0;
- if( *pRoot ){
- mem3.aPool[*pRoot].u.list.prev = i;
- }
- *pRoot = i;
-}
-
-/*
-** Link the chunk at index i into either the appropriate
-** small chunk list, or into the large chunk hash table.
-*/
-static void memsys3Link(u32 i){
- u32 size, hash;
- assert( sqlite3_mutex_held(mem3.mutex) );
- assert( i>=1 );
- assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
- size = mem3.aPool[i-1].u.hdr.size4x/4;
- assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
- assert( size>=2 );
- if( size <= MX_SMALL ){
- memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
- }else{
- hash = size % N_HASH;
- memsys3LinkIntoList(i, &mem3.aiHash[hash]);
- }
-}
-
-/*
-** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
-** will already be held (obtained by code in malloc.c) if
-** sqlite3GlobalConfig.bMemStat is true.
-*/
-static void memsys3Enter(void){
- if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
- mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
- }
- sqlite3_mutex_enter(mem3.mutex);
-}
-static void memsys3Leave(void){
- sqlite3_mutex_leave(mem3.mutex);
-}
-
-/*
-** Called when we are unable to satisfy an allocation of nBytes.
-*/
-static void memsys3OutOfMemory(int nByte){
- if( !mem3.alarmBusy ){
- mem3.alarmBusy = 1;
- assert( sqlite3_mutex_held(mem3.mutex) );
- sqlite3_mutex_leave(mem3.mutex);
- sqlite3_release_memory(nByte);
- sqlite3_mutex_enter(mem3.mutex);
- mem3.alarmBusy = 0;
- }
-}
-
-
-/*
-** Chunk i is a free chunk that has been unlinked. Adjust its
-** size parameters for check-out and return a pointer to the
-** user portion of the chunk.
-*/
-static void *memsys3Checkout(u32 i, u32 nBlock){
- u32 x;
- assert( sqlite3_mutex_held(mem3.mutex) );
- assert( i>=1 );
- assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
- assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
- x = mem3.aPool[i-1].u.hdr.size4x;
- mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
- mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
- mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
- return &mem3.aPool[i];
-}
-
-/*
-** Carve a piece off of the end of the mem3.iMaster free chunk.
-** Return a pointer to the new allocation. Or, if the master chunk
-** is not large enough, return 0.
-*/
-static void *memsys3FromMaster(u32 nBlock){
- assert( sqlite3_mutex_held(mem3.mutex) );
- assert( mem3.szMaster>=nBlock );
- if( nBlock>=mem3.szMaster-1 ){
- /* Use the entire master */
- void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
- mem3.iMaster = 0;
- mem3.szMaster = 0;
- mem3.mnMaster = 0;
- return p;
- }else{
- /* Split the master block. Return the tail. */
- u32 newi, x;
- newi = mem3.iMaster + mem3.szMaster - nBlock;
- assert( newi > mem3.iMaster+1 );
- mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
- mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
- mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
- mem3.szMaster -= nBlock;
- mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
- x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
- mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
- if( mem3.szMaster < mem3.mnMaster ){
- mem3.mnMaster = mem3.szMaster;
- }
- return (void*)&mem3.aPool[newi];
- }
-}
-
-/*
-** *pRoot is the head of a list of free chunks of the same size
-** or same size hash. In other words, *pRoot is an entry in either
-** mem3.aiSmall[] or mem3.aiHash[].
-**
-** This routine examines all entries on the given list and tries
-** to coalesce each entries with adjacent free chunks.
-**
-** If it sees a chunk that is larger than mem3.iMaster, it replaces
-** the current mem3.iMaster with the new larger chunk. In order for
-** this mem3.iMaster replacement to work, the master chunk must be
-** linked into the hash tables. That is not the normal state of
-** affairs, of course. The calling routine must link the master
-** chunk before invoking this routine, then must unlink the (possibly
-** changed) master chunk once this routine has finished.
-*/
-static void memsys3Merge(u32 *pRoot){
- u32 iNext, prev, size, i, x;
-
- assert( sqlite3_mutex_held(mem3.mutex) );
- for(i=*pRoot; i>0; i=iNext){
- iNext = mem3.aPool[i].u.list.next;
- size = mem3.aPool[i-1].u.hdr.size4x;
- assert( (size&1)==0 );
- if( (size&2)==0 ){
- memsys3UnlinkFromList(i, pRoot);
- assert( i > mem3.aPool[i-1].u.hdr.prevSize );
- prev = i - mem3.aPool[i-1].u.hdr.prevSize;
- if( prev==iNext ){
- iNext = mem3.aPool[prev].u.list.next;
- }
- memsys3Unlink(prev);
- size = i + size/4 - prev;
- x = mem3.aPool[prev-1].u.hdr.size4x & 2;
- mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
- mem3.aPool[prev+size-1].u.hdr.prevSize = size;
- memsys3Link(prev);
- i = prev;
- }else{
- size /= 4;
- }
- if( size>mem3.szMaster ){
- mem3.iMaster = i;
- mem3.szMaster = size;
- }
- }
-}
-
-/*
-** Return a block of memory of at least nBytes in size.
-** Return NULL if unable.
-**
-** This function assumes that the necessary mutexes, if any, are
-** already held by the caller. Hence "Unsafe".
-*/
-static void *memsys3MallocUnsafe(int nByte){
- u32 i;
- u32 nBlock;
- u32 toFree;
-
- assert( sqlite3_mutex_held(mem3.mutex) );
- assert( sizeof(Mem3Block)==8 );
- if( nByte<=12 ){
- nBlock = 2;
- }else{
- nBlock = (nByte + 11)/8;
- }
- assert( nBlock>=2 );
-
- /* STEP 1:
- ** Look for an entry of the correct size in either the small
- ** chunk table or in the large chunk hash table. This is
- ** successful most of the time (about 9 times out of 10).
- */
- if( nBlock <= MX_SMALL ){
- i = mem3.aiSmall[nBlock-2];
- if( i>0 ){
- memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
- return memsys3Checkout(i, nBlock);
- }
- }else{
- int hash = nBlock % N_HASH;
- for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
- if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
- memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
- return memsys3Checkout(i, nBlock);
- }
- }
- }
-
- /* STEP 2:
- ** Try to satisfy the allocation by carving a piece off of the end
- ** of the master chunk. This step usually works if step 1 fails.
- */
- if( mem3.szMaster>=nBlock ){
- return memsys3FromMaster(nBlock);
- }
-
-
- /* STEP 3:
- ** Loop through the entire memory pool. Coalesce adjacent free
- ** chunks. Recompute the master chunk as the largest free chunk.
- ** Then try again to satisfy the allocation by carving a piece off
- ** of the end of the master chunk. This step happens very
- ** rarely (we hope!)
- */
- for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
- memsys3OutOfMemory(toFree);
- if( mem3.iMaster ){
- memsys3Link(mem3.iMaster);
- mem3.iMaster = 0;
- mem3.szMaster = 0;
- }
- for(i=0; i=nBlock ){
- return memsys3FromMaster(nBlock);
- }
- }
- }
-
- /* If none of the above worked, then we fail. */
- return 0;
-}
-
-/*
-** Free an outstanding memory allocation.
-**
-** This function assumes that the necessary mutexes, if any, are
-** already held by the caller. Hence "Unsafe".
-*/
-static void memsys3FreeUnsafe(void *pOld){
- Mem3Block *p = (Mem3Block*)pOld;
- int i;
- u32 size, x;
- assert( sqlite3_mutex_held(mem3.mutex) );
- assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
- i = p - mem3.aPool;
- assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
- size = mem3.aPool[i-1].u.hdr.size4x/4;
- assert( i+size<=mem3.nPool+1 );
- mem3.aPool[i-1].u.hdr.size4x &= ~1;
- mem3.aPool[i+size-1].u.hdr.prevSize = size;
- mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
- memsys3Link(i);
-
- /* Try to expand the master using the newly freed chunk */
- if( mem3.iMaster ){
- while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
- size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
- mem3.iMaster -= size;
- mem3.szMaster += size;
- memsys3Unlink(mem3.iMaster);
- x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
- mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
- mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
- }
- x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
- while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
- memsys3Unlink(mem3.iMaster+mem3.szMaster);
- mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
- mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
- mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
- }
- }
-}
-
-/*
-** Return the size of an outstanding allocation, in bytes. The
-** size returned omits the 8-byte header overhead. This only
-** works for chunks that are currently checked out.
-*/
-static int memsys3Size(void *p){
- Mem3Block *pBlock;
- assert( p!=0 );
- pBlock = (Mem3Block*)p;
- assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
- return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
-}
-
-/*
-** Round up a request size to the next valid allocation size.
-*/
-static int memsys3Roundup(int n){
- if( n<=12 ){
- return 12;
- }else{
- return ((n+11)&~7) - 4;
- }
-}
-
-/*
-** Allocate nBytes of memory.
-*/
-static void *memsys3Malloc(int nBytes){
- sqlite3_int64 *p;
- assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
- memsys3Enter();
- p = memsys3MallocUnsafe(nBytes);
- memsys3Leave();
- return (void*)p;
-}
-
-/*
-** Free memory.
-*/
-static void memsys3Free(void *pPrior){
- assert( pPrior );
- memsys3Enter();
- memsys3FreeUnsafe(pPrior);
- memsys3Leave();
-}
-
-/*
-** Change the size of an existing memory allocation
-*/
-static void *memsys3Realloc(void *pPrior, int nBytes){
- int nOld;
- void *p;
- if( pPrior==0 ){
- return sqlite3_malloc(nBytes);
- }
- if( nBytes<=0 ){
- sqlite3_free(pPrior);
- return 0;
- }
- nOld = memsys3Size(pPrior);
- if( nBytes<=nOld && nBytes>=nOld-128 ){
- return pPrior;
- }
- memsys3Enter();
- p = memsys3MallocUnsafe(nBytes);
- if( p ){
- if( nOld>1)!=(size&1) ){
- fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
- assert( 0 );
- break;
- }
- if( size&1 ){
- fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
- }else{
- fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
- i==mem3.iMaster ? " **master**" : "");
- }
- }
- for(i=0; i0; j=mem3.aPool[j].u.list.next){
- fprintf(out, " %p(%d)", &mem3.aPool[j],
- (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
- }
- fprintf(out, "\n");
- }
- for(i=0; i0; j=mem3.aPool[j].u.list.next){
- fprintf(out, " %p(%d)", &mem3.aPool[j],
- (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
- }
- fprintf(out, "\n");
- }
- fprintf(out, "master=%d\n", mem3.iMaster);
- fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
- fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
- sqlite3_mutex_leave(mem3.mutex);
- if( out==stdout ){
- fflush(stdout);
- }else{
- fclose(out);
- }
-#else
- UNUSED_PARAMETER(zFilename);
-#endif
-}
-
-/*
-** 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. The
-** arguments specify the block of memory to manage.
-**
-** This routine is only called by sqlite3_config(), and therefore
-** is not required to be threadsafe (it is not).
-*/
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
- static const sqlite3_mem_methods mempoolMethods = {
- memsys3Malloc,
- memsys3Free,
- memsys3Realloc,
- memsys3Size,
- memsys3Roundup,
- memsys3Init,
- memsys3Shutdown,
- 0
- };
- return &mempoolMethods;
-}
-
-#endif /* SQLITE_ENABLE_MEMSYS3 */
-
-/************** End of mem3.c ************************************************/
-/************** Begin file mem5.c ********************************************/
-/*
-** 2007 October 14
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains the C functions that implement a memory
-** allocation subsystem for use by SQLite.
-**
-** This version of the memory allocation subsystem omits all
-** use of malloc(). The application gives SQLite a block of memory
-** before calling sqlite3_initialize() from which allocations
-** are made and returned by the xMalloc() and xRealloc()
-** implementations. Once sqlite3_initialize() has been called,
-** the amount of memory available to SQLite is fixed and cannot
-** be changed.
-**
-** This version of the memory allocation subsystem is included
-** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
-**
-** This memory allocator uses the following algorithm:
-**
-** 1. All memory allocation sizes are rounded up to a power of 2.
-**
-** 2. If two adjacent free blocks are the halves of a larger block,
-** then the two blocks are coalesced into the single larger block.
-**
-** 3. New memory is allocated from the first available free block.
-**
-** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
-** Concerning Dynamic Storage Allocation". Journal of the Association for
-** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
-**
-** Let n be the size of the largest allocation divided by the minimum
-** allocation size (after rounding all sizes up to a power of 2.) Let M
-** be the maximum amount of memory ever outstanding at one time. Let
-** N be the total amount of memory available for allocation. Robson
-** proved that this memory allocator will never breakdown due to
-** fragmentation as long as the following constraint holds:
-**
-** N >= M*(1 + log2(n)/2) - n + 1
-**
-** The sqlite3_status() logic tracks the maximum values of n and M so
-** that an application can, at any time, verify this constraint.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** This version of the memory allocator is used only when
-** SQLITE_ENABLE_MEMSYS5 is defined.
-*/
-#ifdef SQLITE_ENABLE_MEMSYS5
-
-/*
-** A minimum allocation is an instance of the following structure.
-** Larger allocations are an array of these structures where the
-** size of the array is a power of 2.
-**
-** The size of this object must be a power of two. That fact is
-** verified in memsys5Init().
-*/
-typedef struct Mem5Link Mem5Link;
-struct Mem5Link {
- int next; /* Index of next free chunk */
- int prev; /* Index of previous free chunk */
-};
-
-/*
-** Maximum size of any allocation is ((1<=0 && i=0 && iLogsize<=LOGMAX );
- assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
-
- next = MEM5LINK(i)->next;
- prev = MEM5LINK(i)->prev;
- if( prev<0 ){
- mem5.aiFreelist[iLogsize] = next;
- }else{
- MEM5LINK(prev)->next = next;
- }
- if( next>=0 ){
- MEM5LINK(next)->prev = prev;
- }
-}
-
-/*
-** Link the chunk at mem5.aPool[i] so that is on the iLogsize
-** free list.
-*/
-static void memsys5Link(int i, int iLogsize){
- int x;
- assert( sqlite3_mutex_held(mem5.mutex) );
- assert( i>=0 && i=0 && iLogsize<=LOGMAX );
- assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
-
- x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
- MEM5LINK(i)->prev = -1;
- if( x>=0 ){
- assert( xprev = i;
- }
- mem5.aiFreelist[iLogsize] = i;
-}
-
-/*
-** Obtain or release the mutex needed to access global data structures.
-*/
-static void memsys5Enter(void){
- sqlite3_mutex_enter(mem5.mutex);
-}
-static void memsys5Leave(void){
- sqlite3_mutex_leave(mem5.mutex);
-}
-
-/*
-** Return the size of an outstanding allocation, in bytes.
-** This only works for chunks that are currently checked out.
-*/
-static int memsys5Size(void *p){
- int iSize, i;
- assert( p!=0 );
- i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
- assert( i>=0 && i0 );
-
- /* No more than 1GiB per allocation */
- if( nByte > 0x40000000 ) return 0;
-
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
- /* Keep track of the maximum allocation request. Even unfulfilled
- ** requests are counted */
- if( (u32)nByte>mem5.maxRequest ){
- mem5.maxRequest = nByte;
- }
-#endif
-
-
- /* Round nByte up to the next valid power of two */
- for(iFullSz=mem5.szAtom,iLogsize=0; iFullSzLOGMAX ){
- testcase( sqlite3GlobalConfig.xLog!=0 );
- sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
- return 0;
- }
- i = mem5.aiFreelist[iBin];
- memsys5Unlink(i, iBin);
- while( iBin>iLogsize ){
- int newSize;
-
- iBin--;
- newSize = 1 << iBin;
- mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
- memsys5Link(i+newSize, iBin);
- }
- mem5.aCtrl[i] = iLogsize;
-
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
- /* Update allocator performance statistics. */
- mem5.nAlloc++;
- mem5.totalAlloc += iFullSz;
- mem5.totalExcess += iFullSz - nByte;
- mem5.currentCount++;
- mem5.currentOut += iFullSz;
- if( mem5.maxCount=0 && iBlock0 );
- assert( mem5.currentOut>=(size*mem5.szAtom) );
- mem5.currentCount--;
- mem5.currentOut -= size*mem5.szAtom;
- assert( mem5.currentOut>0 || mem5.currentCount==0 );
- assert( mem5.currentCount>0 || mem5.currentOut==0 );
-#endif
-
- mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
- while( ALWAYS(iLogsize>iLogsize) & 1 ){
- iBuddy = iBlock - size;
- assert( iBuddy>=0 );
- }else{
- iBuddy = iBlock + size;
- if( iBuddy>=mem5.nBlock ) break;
- }
- if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
- memsys5Unlink(iBuddy, iLogsize);
- iLogsize++;
- if( iBuddy0 ){
- memsys5Enter();
- p = memsys5MallocUnsafe(nBytes);
- memsys5Leave();
- }
- return (void*)p;
-}
-
-/*
-** Free memory.
-**
-** The outer layer memory allocator prevents this routine from
-** being called with pPrior==0.
-*/
-static void memsys5Free(void *pPrior){
- assert( pPrior!=0 );
- memsys5Enter();
- memsys5FreeUnsafe(pPrior);
- memsys5Leave();
-}
-
-/*
-** Change the size of an existing memory allocation.
-**
-** The outer layer memory allocator prevents this routine from
-** being called with pPrior==0.
-**
-** nBytes is always a value obtained from a prior call to
-** memsys5Round(). Hence nBytes is always a non-negative power
-** of two. If nBytes==0 that means that an oversize allocation
-** (an allocation larger than 0x40000000) was requested and this
-** routine should return 0 without freeing pPrior.
-*/
-static void *memsys5Realloc(void *pPrior, int nBytes){
- int nOld;
- void *p;
- assert( pPrior!=0 );
- assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
- assert( nBytes>=0 );
- if( nBytes==0 ){
- return 0;
- }
- nOld = memsys5Size(pPrior);
- if( nBytes<=nOld ){
- return pPrior;
- }
- p = memsys5Malloc(nBytes);
- if( p ){
- memcpy(p, pPrior, nOld);
- memsys5Free(pPrior);
- }
- return p;
-}
-
-/*
-** Round up a request size to the next valid allocation size. If
-** the allocation is too large to be handled by this allocation system,
-** return 0.
-**
-** All allocations must be a power of two and must be expressed by a
-** 32-bit signed integer. Hence the largest allocation is 0x40000000
-** or 1073741824 bytes.
-*/
-static int memsys5Roundup(int n){
- int iFullSz;
- if( n > 0x40000000 ) return 0;
- for(iFullSz=mem5.szAtom; iFullSz 0
-** memsys5Log(2) -> 1
-** memsys5Log(4) -> 2
-** memsys5Log(5) -> 3
-** memsys5Log(8) -> 3
-** memsys5Log(9) -> 4
-*/
-static int memsys5Log(int iValue){
- int iLog;
- for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<mem5.szAtom ){
- mem5.szAtom = mem5.szAtom << 1;
- }
-
- mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
- mem5.zPool = zByte;
- mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
-
- for(ii=0; ii<=LOGMAX; ii++){
- mem5.aiFreelist[ii] = -1;
- }
-
- iOffset = 0;
- for(ii=LOGMAX; ii>=0; ii--){
- int nAlloc = (1<mem5.nBlock);
- }
-
- /* If a mutex is required for normal operation, allocate one */
- if( sqlite3GlobalConfig.bMemstat==0 ){
- mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
- }
-
- return SQLITE_OK;
-}
-
-/*
-** Deinitialize this module.
-*/
-static void memsys5Shutdown(void *NotUsed){
- UNUSED_PARAMETER(NotUsed);
- mem5.mutex = 0;
- return;
-}
-
-#ifdef SQLITE_TEST
-/*
-** Open the file indicated and write a log of all unfreed memory
-** allocations into that log.
-*/
-SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
- FILE *out;
- int i, j, n;
- int nMinLog;
-
- if( zFilename==0 || zFilename[0]==0 ){
- out = stdout;
- }else{
- out = fopen(zFilename, "w");
- if( out==0 ){
- fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
- zFilename);
- return;
- }
- }
- memsys5Enter();
- nMinLog = memsys5Log(mem5.szAtom);
- for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
- for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
- fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
- }
- fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
- fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
- fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
- fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
- fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
- fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
- fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
- fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
- memsys5Leave();
- if( out==stdout ){
- fflush(stdout);
- }else{
- fclose(out);
- }
-}
-#endif
-
-/*
-** This routine is the only routine in this file with external
-** linkage. It returns a pointer to a static sqlite3_mem_methods
-** struct populated with the memsys5 methods.
-*/
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
- static const sqlite3_mem_methods memsys5Methods = {
- memsys5Malloc,
- memsys5Free,
- memsys5Realloc,
- memsys5Size,
- memsys5Roundup,
- memsys5Init,
- memsys5Shutdown,
- 0
- };
- return &memsys5Methods;
-}
-
-#endif /* SQLITE_ENABLE_MEMSYS5 */
-
-/************** End of mem5.c ************************************************/
-/************** Begin file mutex.c *******************************************/
-/*
-** 2007 August 14
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains the C functions that implement mutexes.
-**
-** This file contains code that is common across all mutex implementations.
-*/
-/* #include "sqliteInt.h" */
-
-#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
-/*
-** For debugging purposes, record when the mutex subsystem is initialized
-** and uninitialized so that we can assert() if there is an attempt to
-** allocate a mutex while the system is uninitialized.
-*/
-static SQLITE_WSD int mutexIsInit = 0;
-#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
-
-
-#ifndef SQLITE_MUTEX_OMIT
-
-#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
-/*
-** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
-** the implementation of a wrapper around the system default mutex
-** implementation (sqlite3DefaultMutex()).
-**
-** Most calls are passed directly through to the underlying default
-** mutex implementation. Except, if a mutex is configured by calling
-** sqlite3MutexWarnOnContention() on it, then if contention is ever
-** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
-**
-** This type of mutex is used as the database handle mutex when testing
-** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
-*/
-
-/*
-** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
-** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
-** allocated by the system mutex implementation. Variable iType is usually set
-** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
-** or one of the static mutex identifiers. Or, if this is a recursive mutex
-** that has been configured using sqlite3MutexWarnOnContention(), it is
-** set to SQLITE_MUTEX_WARNONCONTENTION.
-*/
-typedef struct CheckMutex CheckMutex;
-struct CheckMutex {
- int iType;
- sqlite3_mutex *mutex;
-};
-
-#define SQLITE_MUTEX_WARNONCONTENTION (-1)
-
-/*
-** Pointer to real mutex methods object used by the CheckMutex
-** implementation. Set by checkMutexInit().
-*/
-static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
-
-#ifdef SQLITE_DEBUG
-static int checkMutexHeld(sqlite3_mutex *p){
- return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
-}
-static int checkMutexNotheld(sqlite3_mutex *p){
- return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
-}
-#endif
-
-/*
-** Initialize and deinitialize the mutex subsystem.
-*/
-static int checkMutexInit(void){
- pGlobalMutexMethods = sqlite3DefaultMutex();
- return SQLITE_OK;
-}
-static int checkMutexEnd(void){
- pGlobalMutexMethods = 0;
- return SQLITE_OK;
-}
-
-/*
-** Allocate a mutex.
-*/
-static sqlite3_mutex *checkMutexAlloc(int iType){
- static CheckMutex staticMutexes[] = {
- {2, 0}, {3, 0}, {4, 0}, {5, 0},
- {6, 0}, {7, 0}, {8, 0}, {9, 0},
- {10, 0}, {11, 0}, {12, 0}, {13, 0}
- };
- CheckMutex *p = 0;
-
- assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
- if( iType<2 ){
- p = sqlite3MallocZero(sizeof(CheckMutex));
- if( p==0 ) return 0;
- p->iType = iType;
- }else{
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( iType-2>=ArraySize(staticMutexes) ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
- p = &staticMutexes[iType-2];
- }
-
- if( p->mutex==0 ){
- p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
- if( p->mutex==0 ){
- if( iType<2 ){
- sqlite3_free(p);
- }
- p = 0;
- }
- }
-
- return (sqlite3_mutex*)p;
-}
-
-/*
-** Free a mutex.
-*/
-static void checkMutexFree(sqlite3_mutex *p){
- assert( SQLITE_MUTEX_RECURSIVE<2 );
- assert( SQLITE_MUTEX_FAST<2 );
- assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
-
-#if SQLITE_ENABLE_API_ARMOR
- if( ((CheckMutex*)p)->iType<2 )
-#endif
- {
- CheckMutex *pCheck = (CheckMutex*)p;
- pGlobalMutexMethods->xMutexFree(pCheck->mutex);
- sqlite3_free(pCheck);
- }
-#ifdef SQLITE_ENABLE_API_ARMOR
- else{
- (void)SQLITE_MISUSE_BKPT;
- }
-#endif
-}
-
-/*
-** Enter the mutex.
-*/
-static void checkMutexEnter(sqlite3_mutex *p){
- CheckMutex *pCheck = (CheckMutex*)p;
- if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
- if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
- return;
- }
- sqlite3_log(SQLITE_MISUSE,
- "illegal multi-threaded access to database connection"
- );
- }
- pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
-}
-
-/*
-** Enter the mutex (do not block).
-*/
-static int checkMutexTry(sqlite3_mutex *p){
- CheckMutex *pCheck = (CheckMutex*)p;
- return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
-}
-
-/*
-** Leave the mutex.
-*/
-static void checkMutexLeave(sqlite3_mutex *p){
- CheckMutex *pCheck = (CheckMutex*)p;
- pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
-}
-
-sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
- static const sqlite3_mutex_methods sMutex = {
- checkMutexInit,
- checkMutexEnd,
- checkMutexAlloc,
- checkMutexFree,
- checkMutexEnter,
- checkMutexTry,
- checkMutexLeave,
-#ifdef SQLITE_DEBUG
- checkMutexHeld,
- checkMutexNotheld
-#else
- 0,
- 0
-#endif
- };
- return &sMutex;
-}
-
-/*
-** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
-** one on which there should be no contention.
-*/
-SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
- if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
- CheckMutex *pCheck = (CheckMutex*)p;
- assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
- pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
- }
-}
-#endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
-
-/*
-** Initialize the mutex system.
-*/
-SQLITE_PRIVATE int sqlite3MutexInit(void){
- int rc = SQLITE_OK;
- if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
- /* If the xMutexAlloc method has not been set, then the user did not
- ** install a mutex implementation via sqlite3_config() prior to
- ** sqlite3_initialize() being called. This block copies pointers to
- ** the default implementation into the sqlite3GlobalConfig structure.
- */
- sqlite3_mutex_methods const *pFrom;
- sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
-
- if( sqlite3GlobalConfig.bCoreMutex ){
-#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
- pFrom = multiThreadedCheckMutex();
-#else
- pFrom = sqlite3DefaultMutex();
-#endif
- }else{
- pFrom = sqlite3NoopMutex();
- }
- pTo->xMutexInit = pFrom->xMutexInit;
- pTo->xMutexEnd = pFrom->xMutexEnd;
- pTo->xMutexFree = pFrom->xMutexFree;
- pTo->xMutexEnter = pFrom->xMutexEnter;
- pTo->xMutexTry = pFrom->xMutexTry;
- pTo->xMutexLeave = pFrom->xMutexLeave;
- pTo->xMutexHeld = pFrom->xMutexHeld;
- pTo->xMutexNotheld = pFrom->xMutexNotheld;
- sqlite3MemoryBarrier();
- pTo->xMutexAlloc = pFrom->xMutexAlloc;
- }
- assert( sqlite3GlobalConfig.mutex.xMutexInit );
- rc = sqlite3GlobalConfig.mutex.xMutexInit();
-
-#ifdef SQLITE_DEBUG
- GLOBAL(int, mutexIsInit) = 1;
-#endif
-
- return rc;
-}
-
-/*
-** Shutdown the mutex system. This call frees resources allocated by
-** sqlite3MutexInit().
-*/
-SQLITE_PRIVATE int sqlite3MutexEnd(void){
- int rc = SQLITE_OK;
- if( sqlite3GlobalConfig.mutex.xMutexEnd ){
- rc = sqlite3GlobalConfig.mutex.xMutexEnd();
- }
-
-#ifdef SQLITE_DEBUG
- GLOBAL(int, mutexIsInit) = 0;
-#endif
-
- return rc;
-}
-
-/*
-** Retrieve a pointer to a static mutex or allocate a new dynamic one.
-*/
-SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
-#ifndef SQLITE_OMIT_AUTOINIT
- if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
- if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
-#endif
- assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
- return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
-}
-
-SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
- if( !sqlite3GlobalConfig.bCoreMutex ){
- return 0;
- }
- assert( GLOBAL(int, mutexIsInit) );
- assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
- return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
-}
-
-/*
-** Free a dynamic mutex.
-*/
-SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
- if( p ){
- assert( sqlite3GlobalConfig.mutex.xMutexFree );
- sqlite3GlobalConfig.mutex.xMutexFree(p);
- }
-}
-
-/*
-** Obtain the mutex p. If some other thread already has the mutex, block
-** until it can be obtained.
-*/
-SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
- if( p ){
- assert( sqlite3GlobalConfig.mutex.xMutexEnter );
- sqlite3GlobalConfig.mutex.xMutexEnter(p);
- }
-}
-
-/*
-** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
-** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
-*/
-SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
- int rc = SQLITE_OK;
- if( p ){
- assert( sqlite3GlobalConfig.mutex.xMutexTry );
- return sqlite3GlobalConfig.mutex.xMutexTry(p);
- }
- return rc;
-}
-
-/*
-** The sqlite3_mutex_leave() routine exits a mutex that was previously
-** entered by the same thread. The behavior is undefined if the mutex
-** is not currently entered. If a NULL pointer is passed as an argument
-** this function is a no-op.
-*/
-SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
- if( p ){
- assert( sqlite3GlobalConfig.mutex.xMutexLeave );
- sqlite3GlobalConfig.mutex.xMutexLeave(p);
- }
-}
-
-#ifndef NDEBUG
-/*
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
-** intended for use inside assert() statements.
-*/
-SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
- assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
- return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
-}
-SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
- assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
- return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
-}
-#endif
-
-#endif /* !defined(SQLITE_MUTEX_OMIT) */
-
-/************** End of mutex.c ***********************************************/
-/************** Begin file mutex_noop.c **************************************/
-/*
-** 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.
-*/
-/* #include "sqliteInt.h" */
-
-#ifndef SQLITE_MUTEX_OMIT
-
-#ifndef SQLITE_DEBUG
-/*
-** Stub routines for all mutex methods.
-**
-** This routines provide no mutual exclusion or error checking.
-*/
-static int noopMutexInit(void){ return SQLITE_OK; }
-static int noopMutexEnd(void){ return SQLITE_OK; }
-static sqlite3_mutex *noopMutexAlloc(int id){
- UNUSED_PARAMETER(id);
- return (sqlite3_mutex*)8;
-}
-static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
-static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
-static int noopMutexTry(sqlite3_mutex *p){
- UNUSED_PARAMETER(p);
- return SQLITE_OK;
-}
-static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
-
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
- static const sqlite3_mutex_methods sMutex = {
- noopMutexInit,
- noopMutexEnd,
- noopMutexAlloc,
- noopMutexFree,
- noopMutexEnter,
- noopMutexTry,
- noopMutexLeave,
-
- 0,
- 0,
- };
-
- return &sMutex;
-}
-#endif /* !SQLITE_DEBUG */
-
-#ifdef SQLITE_DEBUG
-/*
-** In this implementation, error checking is provided for testing
-** and debugging purposes. The mutexes still do not provide any
-** mutual exclusion.
-*/
-
-/*
-** The mutex object
-*/
-typedef struct sqlite3_debug_mutex {
- int id; /* The mutex type */
- int cnt; /* Number of entries without a matching leave */
-} sqlite3_debug_mutex;
-
-/*
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
-** intended for use inside assert() statements.
-*/
-static int debugMutexHeld(sqlite3_mutex *pX){
- sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
- return p==0 || p->cnt>0;
-}
-static int debugMutexNotheld(sqlite3_mutex *pX){
- sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
- return p==0 || p->cnt==0;
-}
-
-/*
-** Initialize and deinitialize the mutex subsystem.
-*/
-static int debugMutexInit(void){ return SQLITE_OK; }
-static int debugMutexEnd(void){ return SQLITE_OK; }
-
-/*
-** The sqlite3_mutex_alloc() routine allocates a new
-** mutex and returns a pointer to it. If it returns NULL
-** that means that a mutex could not be allocated.
-*/
-static sqlite3_mutex *debugMutexAlloc(int id){
- static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
- sqlite3_debug_mutex *pNew = 0;
- switch( id ){
- case SQLITE_MUTEX_FAST:
- case SQLITE_MUTEX_RECURSIVE: {
- pNew = sqlite3Malloc(sizeof(*pNew));
- if( pNew ){
- pNew->id = id;
- pNew->cnt = 0;
- }
- break;
- }
- default: {
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( id-2<0 || id-2>=ArraySize(aStatic) ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
- pNew = &aStatic[id-2];
- pNew->id = id;
- break;
- }
- }
- return (sqlite3_mutex*)pNew;
-}
-
-/*
-** This routine deallocates a previously allocated mutex.
-*/
-static void debugMutexFree(sqlite3_mutex *pX){
- sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
- assert( p->cnt==0 );
- if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
- sqlite3_free(p);
- }else{
-#ifdef SQLITE_ENABLE_API_ARMOR
- (void)SQLITE_MISUSE_BKPT;
-#endif
- }
-}
-
-/*
-** 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;
- assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
- p->cnt++;
-}
-static int debugMutexTry(sqlite3_mutex *pX){
- sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
- assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
- 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;
- assert( debugMutexHeld(pX) );
- p->cnt--;
- assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
-}
-
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
- static const sqlite3_mutex_methods sMutex = {
- debugMutexInit,
- debugMutexEnd,
- debugMutexAlloc,
- debugMutexFree,
- debugMutexEnter,
- debugMutexTry,
- debugMutexLeave,
-
- debugMutexHeld,
- 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.
-*/
-#ifdef SQLITE_MUTEX_NOOP
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
- return sqlite3NoopMutex();
-}
-#endif /* defined(SQLITE_MUTEX_NOOP) */
-#endif /* !defined(SQLITE_MUTEX_OMIT) */
-
-/************** End of mutex_noop.c ******************************************/
-/************** Begin file mutex_unix.c **************************************/
-/*
-** 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 C functions that implement mutexes for pthreads
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** The code in this file is only used if we are compiling threadsafe
-** under unix with pthreads.
-**
-** Note that this implementation requires a version of pthreads that
-** supports recursive mutexes.
-*/
-#ifdef SQLITE_MUTEX_PTHREADS
-
-#include
-
-/*
-** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
-** are necessary under two condidtions: (1) Debug builds and (2) using
-** home-grown mutexes. Encapsulate these conditions into a single #define.
-*/
-#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
-# define SQLITE_MUTEX_NREF 1
-#else
-# define SQLITE_MUTEX_NREF 0
-#endif
-
-/*
-** Each recursive mutex is an instance of the following structure.
-*/
-struct sqlite3_mutex {
- pthread_mutex_t mutex; /* Mutex controlling the lock */
-#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
- int id; /* Mutex type */
-#endif
-#if SQLITE_MUTEX_NREF
- volatile int nRef; /* Number of entrances */
- volatile pthread_t owner; /* Thread that is within this mutex */
- int trace; /* True to trace changes */
-#endif
-};
-#if SQLITE_MUTEX_NREF
-# define SQLITE3_MUTEX_INITIALIZER(id) \
- {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
-#elif defined(SQLITE_ENABLE_API_ARMOR)
-# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
-#else
-#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
-#endif
-
-/*
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
-** intended for use only inside assert() statements. On some platforms,
-** there might be race conditions that can cause these routines to
-** deliver incorrect results. In particular, if pthread_equal() is
-** not an atomic operation, then these routines might delivery
-** incorrect results. On most platforms, pthread_equal() is a
-** comparison of two integers and is therefore atomic. But we are
-** told that HPUX is not such a platform. If so, then these routines
-** will not always work correctly on HPUX.
-**
-** On those platforms where pthread_equal() is not atomic, SQLite
-** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
-** make sure no assert() statements are evaluated and hence these
-** routines are never called.
-*/
-#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
-static int pthreadMutexHeld(sqlite3_mutex *p){
- return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
-}
-static int pthreadMutexNotheld(sqlite3_mutex *p){
- return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
-}
-#endif
-
-/*
-** Try to provide a memory barrier operation, needed for initialization
-** and also for the implementation of xShmBarrier in the VFS in cases
-** where SQLite is compiled without mutexes.
-*/
-SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
-#if defined(SQLITE_MEMORY_BARRIER)
- SQLITE_MEMORY_BARRIER;
-#elif defined(__GNUC__) && GCC_VERSION>=4001000
- __sync_synchronize();
-#endif
-}
-
-/*
-** Initialize and deinitialize the mutex subsystem.
-*/
-static int pthreadMutexInit(void){ return SQLITE_OK; }
-static int pthreadMutexEnd(void){ return SQLITE_OK; }
-
-/*
-** The sqlite3_mutex_alloc() routine allocates a new
-** mutex and returns a pointer to it. If it returns NULL
-** that means that a mutex could not be allocated. 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_OPEN
-**
- SQLITE_MUTEX_STATIC_PRNG
-**
- SQLITE_MUTEX_STATIC_LRU
-**
- SQLITE_MUTEX_STATIC_PMEM
-**
- SQLITE_MUTEX_STATIC_APP1
-**
- SQLITE_MUTEX_STATIC_APP2
-**
- SQLITE_MUTEX_STATIC_APP3
-**
- SQLITE_MUTEX_STATIC_VFS1
-**
- SQLITE_MUTEX_STATIC_VFS2
-**
- SQLITE_MUTEX_STATIC_VFS3
-**
-**
-** The first two constants cause sqlite3_mutex_alloc() to create
-** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
-** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
-** The mutex implementation does not need to make a distinction
-** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
-** not want to. But SQLite will only request a recursive mutex in
-** cases where it really needs one. If a faster non-recursive mutex
-** implementation is available on the host platform, the mutex subsystem
-** might return such a mutex in response to SQLITE_MUTEX_FAST.
-**
-** The other allowed parameters to sqlite3_mutex_alloc() each return
-** a pointer to a static preexisting mutex. 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.
-*/
-static sqlite3_mutex *pthreadMutexAlloc(int iType){
- static sqlite3_mutex staticMutexes[] = {
- SQLITE3_MUTEX_INITIALIZER(2),
- SQLITE3_MUTEX_INITIALIZER(3),
- SQLITE3_MUTEX_INITIALIZER(4),
- SQLITE3_MUTEX_INITIALIZER(5),
- SQLITE3_MUTEX_INITIALIZER(6),
- SQLITE3_MUTEX_INITIALIZER(7),
- SQLITE3_MUTEX_INITIALIZER(8),
- SQLITE3_MUTEX_INITIALIZER(9),
- SQLITE3_MUTEX_INITIALIZER(10),
- SQLITE3_MUTEX_INITIALIZER(11),
- SQLITE3_MUTEX_INITIALIZER(12),
- SQLITE3_MUTEX_INITIALIZER(13)
- };
- sqlite3_mutex *p;
- switch( iType ){
- case SQLITE_MUTEX_RECURSIVE: {
- p = sqlite3MallocZero( sizeof(*p) );
- if( p ){
-#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
- /* If recursive mutexes are not available, we will have to
- ** build our own. See below. */
- pthread_mutex_init(&p->mutex, 0);
-#else
- /* Use a recursive mutex if it is available */
- pthread_mutexattr_t recursiveAttr;
- pthread_mutexattr_init(&recursiveAttr);
- pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
- pthread_mutex_init(&p->mutex, &recursiveAttr);
- pthread_mutexattr_destroy(&recursiveAttr);
-#endif
-#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
- p->id = SQLITE_MUTEX_RECURSIVE;
-#endif
- }
- break;
- }
- case SQLITE_MUTEX_FAST: {
- p = sqlite3MallocZero( sizeof(*p) );
- if( p ){
- pthread_mutex_init(&p->mutex, 0);
-#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
- p->id = SQLITE_MUTEX_FAST;
-#endif
- }
- break;
- }
- default: {
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
- p = &staticMutexes[iType-2];
- break;
- }
- }
-#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
- assert( p==0 || p->id==iType );
-#endif
- return p;
-}
-
-
-/*
-** This routine deallocates a previously
-** allocated mutex. SQLite is careful to deallocate every
-** mutex that it allocates.
-*/
-static void pthreadMutexFree(sqlite3_mutex *p){
- assert( p->nRef==0 );
-#if SQLITE_ENABLE_API_ARMOR
- if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
-#endif
- {
- pthread_mutex_destroy(&p->mutex);
- sqlite3_free(p);
- }
-#ifdef SQLITE_ENABLE_API_ARMOR
- else{
- (void)SQLITE_MISUSE_BKPT;
- }
-#endif
-}
-
-/*
-** 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 pthreadMutexEnter(sqlite3_mutex *p){
- assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
-
-#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
- /* If recursive mutexes are not available, then we have to grow
- ** our own. This implementation assumes that pthread_equal()
- ** is atomic - that it cannot be deceived into thinking self
- ** and p->owner are equal if p->owner changes between two values
- ** that are not equal to self while the comparison is taking place.
- ** This implementation also assumes a coherent cache - that
- ** separate processes cannot read different values from the same
- ** address at the same time. If either of these two conditions
- ** are not met, then the mutexes will fail and problems will result.
- */
- {
- pthread_t self = pthread_self();
- if( p->nRef>0 && pthread_equal(p->owner, self) ){
- p->nRef++;
- }else{
- pthread_mutex_lock(&p->mutex);
- assert( p->nRef==0 );
- p->owner = self;
- p->nRef = 1;
- }
- }
-#else
- /* Use the built-in recursive mutexes if they are available.
- */
- pthread_mutex_lock(&p->mutex);
-#if SQLITE_MUTEX_NREF
- assert( p->nRef>0 || p->owner==0 );
- p->owner = pthread_self();
- p->nRef++;
-#endif
-#endif
-
-#ifdef SQLITE_DEBUG
- if( p->trace ){
- printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
- }
-#endif
-}
-static int pthreadMutexTry(sqlite3_mutex *p){
- int rc;
- assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
-
-#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
- /* If recursive mutexes are not available, then we have to grow
- ** our own. This implementation assumes that pthread_equal()
- ** is atomic - that it cannot be deceived into thinking self
- ** and p->owner are equal if p->owner changes between two values
- ** that are not equal to self while the comparison is taking place.
- ** This implementation also assumes a coherent cache - that
- ** separate processes cannot read different values from the same
- ** address at the same time. If either of these two conditions
- ** are not met, then the mutexes will fail and problems will result.
- */
- {
- pthread_t self = pthread_self();
- if( p->nRef>0 && pthread_equal(p->owner, self) ){
- p->nRef++;
- rc = SQLITE_OK;
- }else if( pthread_mutex_trylock(&p->mutex)==0 ){
- assert( p->nRef==0 );
- p->owner = self;
- p->nRef = 1;
- rc = SQLITE_OK;
- }else{
- rc = SQLITE_BUSY;
- }
- }
-#else
- /* Use the built-in recursive mutexes if they are available.
- */
- if( pthread_mutex_trylock(&p->mutex)==0 ){
-#if SQLITE_MUTEX_NREF
- p->owner = pthread_self();
- p->nRef++;
-#endif
- rc = SQLITE_OK;
- }else{
- rc = SQLITE_BUSY;
- }
-#endif
-
-#ifdef SQLITE_DEBUG
- if( rc==SQLITE_OK && p->trace ){
- printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
- }
-#endif
- return rc;
-}
-
-/*
-** The sqlite3_mutex_leave() routine exits a mutex that was
-** previously entered by the same thread. The behavior
-** is undefined if the mutex is not currently entered or
-** is not currently allocated. SQLite will never do either.
-*/
-static void pthreadMutexLeave(sqlite3_mutex *p){
- assert( pthreadMutexHeld(p) );
-#if SQLITE_MUTEX_NREF
- p->nRef--;
- if( p->nRef==0 ) p->owner = 0;
-#endif
- assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
-
-#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
- if( p->nRef==0 ){
- pthread_mutex_unlock(&p->mutex);
- }
-#else
- pthread_mutex_unlock(&p->mutex);
-#endif
-
-#ifdef SQLITE_DEBUG
- if( p->trace ){
- printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
- }
-#endif
-}
-
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
- static const sqlite3_mutex_methods sMutex = {
- pthreadMutexInit,
- pthreadMutexEnd,
- pthreadMutexAlloc,
- pthreadMutexFree,
- pthreadMutexEnter,
- pthreadMutexTry,
- pthreadMutexLeave,
-#ifdef SQLITE_DEBUG
- pthreadMutexHeld,
- pthreadMutexNotheld
-#else
- 0,
- 0
-#endif
- };
-
- return &sMutex;
-}
-
-#endif /* SQLITE_MUTEX_PTHREADS */
-
-/************** End of mutex_unix.c ******************************************/
-/************** Begin file mutex_w32.c ***************************************/
-/*
-** 2007 August 14
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains the C functions that implement mutexes for Win32.
-*/
-/* #include "sqliteInt.h" */
-
-#if SQLITE_OS_WIN
-/*
-** Include code that is common to all os_*.c files
-*/
-/************** Include os_common.h in the middle of mutex_w32.c *************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 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.
-*/
-#ifndef _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.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing. Normally turned off. Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 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.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_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 (defined(__GNUC__) || defined(_MSC_VER)) && \
- (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
- #if defined(__GNUC__)
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned int lo, hi;
- __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
- return (sqlite_uint64)hi << 32 | lo;
- }
-
- #elif defined(_MSC_VER)
-
- __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
- __asm {
- rdtsc
- ret ; return value at EDX:EAX
- }
- }
-
- #endif
-
-#elif (defined(__GNUC__) && defined(__x86_64__))
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned long val;
- __asm__ __volatile__ ("rdtsc" : "=A" (val));
- return val;
- }
-
-#elif (defined(__GNUC__) && defined(__ppc__))
-
- __inline__ sqlite_uint64 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.
- */
-SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START g_start=sqlite3Hwtime()
-#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED ((sqlite_uint64)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 defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE) \
- if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
- || sqlite3_io_error_pending-- == 1 ) \
- { local_ioerr(); CODE; }
-static void local_ioerr(){
- IOTRACE(("IOERR\n"));
- sqlite3_io_error_hit++;
- if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#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--; \
- } \
- }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X) sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in mutex_w32.c ******************/
-
-/*
-** Include the header file for the Windows VFS.
-*/
-/************** Include os_win.h in the middle of mutex_w32.c ****************/
-/************** Begin file os_win.h ******************************************/
-/*
-** 2013 November 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 code that is specific to Windows.
-*/
-#ifndef SQLITE_OS_WIN_H
-#define SQLITE_OS_WIN_H
-
-/*
-** Include the primary Windows SDK header file.
-*/
-#include "windows.h"
-
-#ifdef __CYGWIN__
-# include
-# include /* amalgamator: dontcache */
-#endif
-
-/*
-** Determine if we are dealing with Windows NT.
-**
-** We ought to be able to determine if we are compiling for Windows 9x or
-** Windows NT using the _WIN32_WINNT macro as follows:
-**
-** #if defined(_WIN32_WINNT)
-** # define SQLITE_OS_WINNT 1
-** #else
-** # define SQLITE_OS_WINNT 0
-** #endif
-**
-** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
-** it ought to, so the above test does not work. We'll just assume that
-** everything is Windows NT unless the programmer explicitly says otherwise
-** by setting SQLITE_OS_WINNT to 0.
-*/
-#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
-# define SQLITE_OS_WINNT 1
-#endif
-
-/*
-** Determine if we are dealing with Windows CE - which has a much reduced
-** API.
-*/
-#if defined(_WIN32_WCE)
-# define SQLITE_OS_WINCE 1
-#else
-# define SQLITE_OS_WINCE 0
-#endif
-
-/*
-** Determine if we are dealing with WinRT, which provides only a subset of
-** the full Win32 API.
-*/
-#if !defined(SQLITE_OS_WINRT)
-# define SQLITE_OS_WINRT 0
-#endif
-
-/*
-** For WinCE, some API function parameters do not appear to be declared as
-** volatile.
-*/
-#if SQLITE_OS_WINCE
-# define SQLITE_WIN32_VOLATILE
-#else
-# define SQLITE_WIN32_VOLATILE volatile
-#endif
-
-/*
-** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
-** functions are not available (e.g. those not using MSVC, Cygwin, etc).
-*/
-#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
- SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
-# define SQLITE_OS_WIN_THREADS 1
-#else
-# define SQLITE_OS_WIN_THREADS 0
-#endif
-
-#endif /* SQLITE_OS_WIN_H */
-
-/************** End of os_win.h **********************************************/
-/************** Continuing where we left off in mutex_w32.c ******************/
-#endif
-
-/*
-** The code in this file is only used if we are compiling multithreaded
-** on a Win32 system.
-*/
-#ifdef SQLITE_MUTEX_W32
-
-/*
-** Each recursive mutex is an instance of the following structure.
-*/
-struct sqlite3_mutex {
- CRITICAL_SECTION mutex; /* Mutex controlling the lock */
- int id; /* Mutex type */
-#ifdef SQLITE_DEBUG
- volatile int nRef; /* Number of enterances */
- volatile DWORD owner; /* Thread holding this mutex */
- volatile LONG trace; /* True to trace changes */
-#endif
-};
-
-/*
-** These are the initializer values used when declaring a "static" mutex
-** on Win32. It should be noted that all mutexes require initialization
-** on the Win32 platform.
-*/
-#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
-
-#ifdef SQLITE_DEBUG
-#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
- 0L, (DWORD)0, 0 }
-#else
-#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
-#endif
-
-#ifdef SQLITE_DEBUG
-/*
-** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
-** intended for use only inside assert() statements.
-*/
-static int winMutexHeld(sqlite3_mutex *p){
- return p->nRef!=0 && p->owner==GetCurrentThreadId();
-}
-
-static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
- return p->nRef==0 || p->owner!=tid;
-}
-
-static int winMutexNotheld(sqlite3_mutex *p){
- DWORD tid = GetCurrentThreadId();
- return winMutexNotheld2(p, tid);
-}
-#endif
-
-/*
-** Try to provide a memory barrier operation, needed for initialization
-** and also for the xShmBarrier method of the VFS in cases when SQLite is
-** compiled without mutexes (SQLITE_THREADSAFE=0).
-*/
-SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
-#if defined(SQLITE_MEMORY_BARRIER)
- SQLITE_MEMORY_BARRIER;
-#elif defined(__GNUC__)
- __sync_synchronize();
-#elif MSVC_VERSION>=1300
- _ReadWriteBarrier();
-#elif defined(MemoryBarrier)
- MemoryBarrier();
-#endif
-}
-
-/*
-** Initialize and deinitialize the mutex subsystem.
-*/
-static sqlite3_mutex winMutex_staticMutexes[] = {
- SQLITE3_MUTEX_INITIALIZER(2),
- SQLITE3_MUTEX_INITIALIZER(3),
- SQLITE3_MUTEX_INITIALIZER(4),
- SQLITE3_MUTEX_INITIALIZER(5),
- SQLITE3_MUTEX_INITIALIZER(6),
- SQLITE3_MUTEX_INITIALIZER(7),
- SQLITE3_MUTEX_INITIALIZER(8),
- SQLITE3_MUTEX_INITIALIZER(9),
- SQLITE3_MUTEX_INITIALIZER(10),
- SQLITE3_MUTEX_INITIALIZER(11),
- SQLITE3_MUTEX_INITIALIZER(12),
- SQLITE3_MUTEX_INITIALIZER(13)
-};
-
-static int winMutex_isInit = 0;
-static int winMutex_isNt = -1; /* <0 means "need to query" */
-
-/* As the winMutexInit() and winMutexEnd() functions are called as part
-** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
-** "interlocked" magic used here is probably not strictly necessary.
-*/
-static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
-
-SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
-SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
-
-static int winMutexInit(void){
- /* The first to increment to 1 does actual initialization */
- if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
- int i;
- for(i=0; i
-** - SQLITE_MUTEX_FAST
-**
- SQLITE_MUTEX_RECURSIVE
-**
- SQLITE_MUTEX_STATIC_MASTER
-**
- SQLITE_MUTEX_STATIC_MEM
-**
- SQLITE_MUTEX_STATIC_OPEN
-**
- SQLITE_MUTEX_STATIC_PRNG
-**
- SQLITE_MUTEX_STATIC_LRU
-**
- SQLITE_MUTEX_STATIC_PMEM
-**
- SQLITE_MUTEX_STATIC_APP1
-**
- SQLITE_MUTEX_STATIC_APP2
-**
- SQLITE_MUTEX_STATIC_APP3
-**
- SQLITE_MUTEX_STATIC_VFS1
-**
- SQLITE_MUTEX_STATIC_VFS2
-**
- SQLITE_MUTEX_STATIC_VFS3
-**
-**
-** The first two constants cause sqlite3_mutex_alloc() to create
-** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
-** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
-** The mutex implementation does not need to make a distinction
-** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
-** not want to. But SQLite will only request a recursive mutex in
-** cases where it really needs one. If a faster non-recursive mutex
-** implementation is available on the host platform, the mutex subsystem
-** might return such a mutex in response to SQLITE_MUTEX_FAST.
-**
-** The other allowed parameters to sqlite3_mutex_alloc() each return
-** a pointer to a static preexisting mutex. 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.
-*/
-static sqlite3_mutex *winMutexAlloc(int iType){
- sqlite3_mutex *p;
-
- switch( iType ){
- case SQLITE_MUTEX_FAST:
- case SQLITE_MUTEX_RECURSIVE: {
- p = sqlite3MallocZero( sizeof(*p) );
- if( p ){
- p->id = iType;
-#ifdef SQLITE_DEBUG
-#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
- p->trace = 1;
-#endif
-#endif
-#if SQLITE_OS_WINRT
- InitializeCriticalSectionEx(&p->mutex, 0, 0);
-#else
- InitializeCriticalSection(&p->mutex);
-#endif
- }
- break;
- }
- default: {
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
- p = &winMutex_staticMutexes[iType-2];
-#ifdef SQLITE_DEBUG
-#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
- InterlockedCompareExchange(&p->trace, 1, 0);
-#endif
-#endif
- break;
- }
- }
- assert( p==0 || p->id==iType );
- return p;
-}
-
-
-/*
-** This routine deallocates a previously
-** allocated mutex. SQLite is careful to deallocate every
-** mutex that it allocates.
-*/
-static void winMutexFree(sqlite3_mutex *p){
- assert( p );
- assert( p->nRef==0 && p->owner==0 );
- if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
- DeleteCriticalSection(&p->mutex);
- sqlite3_free(p);
- }else{
-#ifdef SQLITE_ENABLE_API_ARMOR
- (void)SQLITE_MISUSE_BKPT;
-#endif
- }
-}
-
-/*
-** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
-** to enter a mutex. If another thread is already within the mutex,
-** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
-** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
-** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
-** be entered multiple times by the same thread. In such cases the,
-** mutex must be exited an equal number of times before another thread
-** can enter. If the same thread tries to enter any other kind of mutex
-** more than once, the behavior is undefined.
-*/
-static void winMutexEnter(sqlite3_mutex *p){
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
- DWORD tid = GetCurrentThreadId();
-#endif
-#ifdef SQLITE_DEBUG
- assert( p );
- assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
-#else
- assert( p );
-#endif
- assert( winMutex_isInit==1 );
- EnterCriticalSection(&p->mutex);
-#ifdef SQLITE_DEBUG
- assert( p->nRef>0 || p->owner==0 );
- p->owner = tid;
- p->nRef++;
- if( p->trace ){
- OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
- tid, p->id, p, p->trace, p->nRef));
- }
-#endif
-}
-
-static int winMutexTry(sqlite3_mutex *p){
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
- DWORD tid = GetCurrentThreadId();
-#endif
- int rc = SQLITE_BUSY;
- assert( p );
- assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
- /*
- ** The sqlite3_mutex_try() routine is very rarely used, and when it
- ** is used it is merely an optimization. So it is OK for it to always
- ** fail.
- **
- ** The TryEnterCriticalSection() interface is only available on WinNT.
- ** And some windows compilers complain if you try to use it without
- ** first doing some #defines that prevent SQLite from building on Win98.
- ** For that reason, we will omit this optimization for now. See
- ** ticket #2685.
- */
-#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
- assert( winMutex_isInit==1 );
- assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
- if( winMutex_isNt<0 ){
- winMutex_isNt = sqlite3_win32_is_nt();
- }
- assert( winMutex_isNt==0 || winMutex_isNt==1 );
- if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
-#ifdef SQLITE_DEBUG
- p->owner = tid;
- p->nRef++;
-#endif
- rc = SQLITE_OK;
- }
-#else
- UNUSED_PARAMETER(p);
-#endif
-#ifdef SQLITE_DEBUG
- if( p->trace ){
- OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
- tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
- }
-#endif
- return rc;
-}
-
-/*
-** The sqlite3_mutex_leave() routine exits a mutex that was
-** previously entered by the same thread. The behavior
-** is undefined if the mutex is not currently entered or
-** is not currently allocated. SQLite will never do either.
-*/
-static void winMutexLeave(sqlite3_mutex *p){
-#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
- DWORD tid = GetCurrentThreadId();
-#endif
- assert( p );
-#ifdef SQLITE_DEBUG
- assert( p->nRef>0 );
- assert( p->owner==tid );
- p->nRef--;
- if( p->nRef==0 ) p->owner = 0;
- assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
-#endif
- assert( winMutex_isInit==1 );
- LeaveCriticalSection(&p->mutex);
-#ifdef SQLITE_DEBUG
- if( p->trace ){
- OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
- tid, p->id, p, p->trace, p->nRef));
- }
-#endif
-}
-
-SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
- static const sqlite3_mutex_methods sMutex = {
- winMutexInit,
- winMutexEnd,
- winMutexAlloc,
- winMutexFree,
- winMutexEnter,
- winMutexTry,
- winMutexLeave,
-#ifdef SQLITE_DEBUG
- winMutexHeld,
- winMutexNotheld
-#else
- 0,
- 0
-#endif
- };
- return &sMutex;
-}
-
-#endif /* SQLITE_MUTEX_W32 */
-
-/************** End of mutex_w32.c *******************************************/
-/************** Begin file malloc.c ******************************************/
-/*
-** 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.
-*/
-/* #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.
-*/
-SQLITE_API int sqlite3_release_memory(int n){
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
- return sqlite3PcacheReleaseMemory(n);
-#else
- /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
- ** is a no-op returning zero if SQLite is not compiled with
- ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
- UNUSED_PARAMETER(n);
- return 0;
-#endif
-}
-
-/*
-** State information local to the memory allocation subsystem.
-*/
-static SQLITE_WSD struct Mem0Global {
- sqlite3_mutex *mutex; /* Mutex to serialize access */
- sqlite3_int64 alarmThreshold; /* The soft heap limit */
-
- /*
- ** True if heap is nearly "full" where "full" is defined by the
- ** sqlite3_soft_heap_limit() setting.
- */
- int nearlyFull;
-} mem0 = { 0, 0, 0 };
-
-#define mem0 GLOBAL(struct Mem0Global, mem0)
-
-/*
-** Return the memory allocator mutex. sqlite3_status() needs it.
-*/
-SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
- return mem0.mutex;
-}
-
-#ifndef SQLITE_OMIT_DEPRECATED
-/*
-** Deprecated external interface. It used to set an alarm callback
-** that was invoked when memory usage grew too large. Now it is a
-** no-op.
-*/
-SQLITE_API int sqlite3_memory_alarm(
- void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
- void *pArg,
- sqlite3_int64 iThreshold
-){
- (void)xCallback;
- (void)pArg;
- (void)iThreshold;
- return SQLITE_OK;
-}
-#endif
-
-/*
-** Set the soft heap-size limit for the library. Passing a zero or
-** negative value indicates no limit.
-*/
-SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
- sqlite3_int64 priorLimit;
- sqlite3_int64 excess;
- sqlite3_int64 nUsed;
-#ifndef SQLITE_OMIT_AUTOINIT
- int rc = sqlite3_initialize();
- if( rc ) return -1;
-#endif
- sqlite3_mutex_enter(mem0.mutex);
- priorLimit = mem0.alarmThreshold;
- if( n<0 ){
- sqlite3_mutex_leave(mem0.mutex);
- return priorLimit;
- }
- mem0.alarmThreshold = n;
- nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
- mem0.nearlyFull = (n>0 && n<=nUsed);
- sqlite3_mutex_leave(mem0.mutex);
- excess = sqlite3_memory_used() - n;
- if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
- return priorLimit;
-}
-SQLITE_API void sqlite3_soft_heap_limit(int n){
- if( n<0 ) n = 0;
- sqlite3_soft_heap_limit64(n);
-}
-
-/*
-** Initialize the memory allocation subsystem.
-*/
-SQLITE_PRIVATE int sqlite3MallocInit(void){
- int rc;
- if( sqlite3GlobalConfig.m.xMalloc==0 ){
- sqlite3MemSetDefault();
- }
- memset(&mem0, 0, sizeof(mem0));
- mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
- if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
- || sqlite3GlobalConfig.nPage<=0 ){
- sqlite3GlobalConfig.pPage = 0;
- sqlite3GlobalConfig.szPage = 0;
- }
- rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
- if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
- return rc;
-}
-
-/*
-** Return true if the heap is currently under memory pressure - in other
-** words if the amount of heap used is close to the limit set by
-** sqlite3_soft_heap_limit().
-*/
-SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
- return mem0.nearlyFull;
-}
-
-/*
-** Deinitialize the memory allocation subsystem.
-*/
-SQLITE_PRIVATE void sqlite3MallocEnd(void){
- if( sqlite3GlobalConfig.m.xShutdown ){
- sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
- }
- memset(&mem0, 0, sizeof(mem0));
-}
-
-/*
-** Return the amount of memory currently checked out.
-*/
-SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
- sqlite3_int64 res, mx;
- sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
- return res;
-}
-
-/*
-** Return the maximum amount of memory that has ever been
-** checked out since either the beginning of this process
-** or since the most recent reset.
-*/
-SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
- sqlite3_int64 res, mx;
- sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
- return mx;
-}
-
-/*
-** Trigger the alarm
-*/
-static void sqlite3MallocAlarm(int nByte){
- if( mem0.alarmThreshold<=0 ) return;
- sqlite3_mutex_leave(mem0.mutex);
- sqlite3_release_memory(nByte);
- sqlite3_mutex_enter(mem0.mutex);
-}
-
-/*
-** Do a memory allocation with statistics and alarms. Assume the
-** lock is already held.
-*/
-static void mallocWithAlarm(int n, void **pp){
- void *p;
- int nFull;
- assert( sqlite3_mutex_held(mem0.mutex) );
- assert( n>0 );
-
- /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
- ** implementation of malloc_good_size(), which must be called in debug
- ** mode and specifically when the DMD "Dark Matter Detector" is enabled
- ** or else a crash results. Hence, do not attempt to optimize out the
- ** following xRoundup() call. */
- nFull = sqlite3GlobalConfig.m.xRoundup(n);
-
-#ifdef SQLITE_MAX_MEMORY
- if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
- *pp = 0;
- return;
- }
-#endif
-
- sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
- if( mem0.alarmThreshold>0 ){
- sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
- if( nUsed >= mem0.alarmThreshold - nFull ){
- mem0.nearlyFull = 1;
- sqlite3MallocAlarm(nFull);
- }else{
- mem0.nearlyFull = 0;
- }
- }
- p = sqlite3GlobalConfig.m.xMalloc(nFull);
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
- if( p==0 && mem0.alarmThreshold>0 ){
- sqlite3MallocAlarm(nFull);
- p = sqlite3GlobalConfig.m.xMalloc(nFull);
- }
-#endif
- if( p ){
- nFull = sqlite3MallocSize(p);
- sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
- sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
- }
- *pp = p;
-}
-
-/*
-** Allocate memory. This routine is like sqlite3_malloc() except that it
-** assumes the memory subsystem has already been initialized.
-*/
-SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
- void *p;
- 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 = 0;
- }else if( sqlite3GlobalConfig.bMemstat ){
- sqlite3_mutex_enter(mem0.mutex);
- mallocWithAlarm((int)n, &p);
- sqlite3_mutex_leave(mem0.mutex);
- }else{
- p = sqlite3GlobalConfig.m.xMalloc((int)n);
- }
- assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
- 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.
-*/
-SQLITE_API void *sqlite3_malloc(int n){
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return n<=0 ? 0 : sqlite3Malloc(n);
-}
-SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return sqlite3Malloc(n);
-}
-
-/*
-** TRUE if p is a lookaside memory allocation from db
-*/
-#ifndef SQLITE_OMIT_LOOKASIDE
-static int isLookaside(sqlite3 *db, void *p){
- return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
-}
-#else
-#define isLookaside(A,B) 0
-#endif
-
-/*
-** Return the size of a memory allocation previously obtained from
-** sqlite3Malloc() or sqlite3_malloc().
-*/
-SQLITE_PRIVATE int sqlite3MallocSize(void *p){
- assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
- return sqlite3GlobalConfig.m.xSize(p);
-}
-SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
- assert( p!=0 );
- if( db==0 || !isLookaside(db,p) ){
-#ifdef SQLITE_DEBUG
- if( db==0 ){
- assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
- assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
- }else{
- assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- }
-#endif
- return sqlite3GlobalConfig.m.xSize(p);
- }else{
- assert( sqlite3_mutex_held(db->mutex) );
- return db->lookaside.sz;
- }
-}
-SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
- assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
- assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
- return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
-}
-
-/*
-** Free memory previously obtained from sqlite3Malloc().
-*/
-SQLITE_API void sqlite3_free(void *p){
- if( p==0 ) return; /* IMP: R-49053-54554 */
- assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
- assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
- if( sqlite3GlobalConfig.bMemstat ){
- sqlite3_mutex_enter(mem0.mutex);
- sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
- sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
- sqlite3GlobalConfig.m.xFree(p);
- sqlite3_mutex_leave(mem0.mutex);
- }else{
- sqlite3GlobalConfig.m.xFree(p);
- }
-}
-
-/*
-** Add the size of memory allocation "p" to the count in
-** *db->pnBytesFreed.
-*/
-static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
- *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
-}
-
-/*
-** Free memory that might be associated with a particular database
-** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
-** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
-*/
-SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
- assert( db==0 || sqlite3_mutex_held(db->mutex) );
- assert( p!=0 );
- if( db ){
- if( db->pnBytesFreed ){
- measureAllocationSize(db, p);
- return;
- }
- if( isLookaside(db, p) ){
- LookasideSlot *pBuf = (LookasideSlot*)p;
-#ifdef SQLITE_DEBUG
- /* Trash all content in the buffer being freed */
- memset(p, 0xaa, db->lookaside.sz);
-#endif
- pBuf->pNext = db->lookaside.pFree;
- db->lookaside.pFree = pBuf;
- return;
- }
- }
- assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
- sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
- sqlite3_free(p);
-}
-SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
- assert( db==0 || sqlite3_mutex_held(db->mutex) );
- if( p ) sqlite3DbFreeNN(db, p);
-}
-
-/*
-** Change the size of an existing memory allocation
-*/
-SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
- int nOld, nNew, nDiff;
- void *pNew;
- assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
- assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
- if( pOld==0 ){
- return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
- }
- if( nBytes==0 ){
- sqlite3_free(pOld); /* IMP: R-26507-47431 */
- return 0;
- }
- if( nBytes>=0x7fffff00 ){
- /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
- return 0;
- }
- nOld = sqlite3MallocSize(pOld);
- /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
- ** argument to xRealloc is always a value returned by a prior call to
- ** xRoundup. */
- nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
- if( nOld==nNew ){
- pNew = pOld;
- }else if( sqlite3GlobalConfig.bMemstat ){
- sqlite3_mutex_enter(mem0.mutex);
- sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
- nDiff = nNew - nOld;
- if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
- mem0.alarmThreshold-nDiff ){
- sqlite3MallocAlarm(nDiff);
- }
- pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
- if( pNew==0 && mem0.alarmThreshold>0 ){
- sqlite3MallocAlarm((int)nBytes);
- pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
- }
- if( pNew ){
- nNew = sqlite3MallocSize(pNew);
- sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
- }
- sqlite3_mutex_leave(mem0.mutex);
- }else{
- pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
- }
- assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
- return pNew;
-}
-
-/*
-** The public interface to sqlite3Realloc. Make sure that the memory
-** subsystem is initialized prior to invoking sqliteRealloc.
-*/
-SQLITE_API void *sqlite3_realloc(void *pOld, int n){
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- if( n<0 ) n = 0; /* IMP: R-26507-47431 */
- return sqlite3Realloc(pOld, n);
-}
-SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return sqlite3Realloc(pOld, n);
-}
-
-
-/*
-** Allocate and zero memory.
-*/
-SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
- void *p = sqlite3Malloc(n);
- if( p ){
- memset(p, 0, (size_t)n);
- }
- return p;
-}
-
-/*
-** Allocate and zero memory. If the allocation fails, make
-** the mallocFailed flag in the connection pointer.
-*/
-SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
- void *p;
- testcase( db==0 );
- p = sqlite3DbMallocRaw(db, n);
- if( p ) memset(p, 0, (size_t)n);
- return p;
-}
-
-
-/* Finish the work of sqlite3DbMallocRawNN for the unusual and
-** slower case when the allocation cannot be fulfilled using lookaside.
-*/
-static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
- void *p;
- assert( db!=0 );
- p = sqlite3Malloc(n);
- if( !p ) sqlite3OomFault(db);
- sqlite3MemdebugSetType(p,
- (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
- return p;
-}
-
-/*
-** Allocate memory, either lookaside (if possible) or heap.
-** If the allocation fails, set 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.
-**
-** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
-** not a NULL pointer.
-*/
-SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
- void *p;
- if( db ) return sqlite3DbMallocRawNN(db, n);
- p = sqlite3Malloc(n);
- sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
- return p;
-}
-SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
-#ifndef SQLITE_OMIT_LOOKASIDE
- LookasideSlot *pBuf;
- assert( db!=0 );
- assert( sqlite3_mutex_held(db->mutex) );
- assert( db->pnBytesFreed==0 );
- if( db->lookaside.bDisable==0 ){
- assert( db->mallocFailed==0 );
- if( n>db->lookaside.sz ){
- db->lookaside.anStat[1]++;
- }else if( (pBuf = db->lookaside.pFree)!=0 ){
- db->lookaside.pFree = pBuf->pNext;
- db->lookaside.anStat[0]++;
- return (void*)pBuf;
- }else if( (pBuf = db->lookaside.pInit)!=0 ){
- db->lookaside.pInit = pBuf->pNext;
- db->lookaside.anStat[0]++;
- return (void*)pBuf;
- }else{
- db->lookaside.anStat[2]++;
- }
- }else if( db->mallocFailed ){
- return 0;
- }
-#else
- assert( db!=0 );
- assert( sqlite3_mutex_held(db->mutex) );
- assert( db->pnBytesFreed==0 );
- if( db->mallocFailed ){
- return 0;
- }
-#endif
- return dbMallocRawFinish(db, n);
-}
-
-/* Forward declaration */
-static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
-
-/*
-** Resize the block of memory pointed to by p to n bytes. If the
-** resize fails, set the mallocFailed flag in the connection object.
-*/
-SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
- assert( db!=0 );
- if( p==0 ) return sqlite3DbMallocRawNN(db, n);
- assert( sqlite3_mutex_held(db->mutex) );
- if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
- return dbReallocFinish(db, p, n);
-}
-static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
- void *pNew = 0;
- assert( db!=0 );
- assert( p!=0 );
- if( db->mallocFailed==0 ){
- if( isLookaside(db, p) ){
- pNew = sqlite3DbMallocRawNN(db, n);
- if( pNew ){
- memcpy(pNew, p, db->lookaside.sz);
- sqlite3DbFree(db, p);
- }
- }else{
- assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
- sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
- pNew = sqlite3_realloc64(p, n);
- if( !pNew ){
- sqlite3OomFault(db);
- }
- sqlite3MemdebugSetType(pNew,
- (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
- }
- }
- return pNew;
-}
-
-/*
-** Attempt to reallocate p. If the reallocation fails, then free p
-** and set the mallocFailed flag in the database connection.
-*/
-SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
- void *pNew;
- pNew = sqlite3DbRealloc(db, p, n);
- if( !pNew ){
- sqlite3DbFree(db, 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.
-*/
-SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
- char *zNew;
- size_t n;
- if( z==0 ){
- return 0;
- }
- n = strlen(z) + 1;
- zNew = sqlite3DbMallocRaw(db, n);
- if( zNew ){
- memcpy(zNew, z, n);
- }
- return zNew;
-}
-SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
- char *zNew;
- assert( db!=0 );
- if( z==0 ){
- return 0;
- }
- assert( (n&0x7fffffff)==n );
- zNew = sqlite3DbMallocRawNN(db, n+1);
- if( zNew ){
- memcpy(zNew, z, (size_t)n);
- zNew[n] = 0;
- }
- return zNew;
-}
-
-/*
-** The text between zStart and zEnd represents a phrase within a larger
-** SQL statement. Make a copy of this phrase in space obtained form
-** sqlite3DbMalloc(). Omit leading and trailing whitespace.
-*/
-SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
- int n;
- while( sqlite3Isspace(zStart[0]) ) zStart++;
- n = (int)(zEnd - zStart);
- while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
- return sqlite3DbStrNDup(db, zStart, n);
-}
-
-/*
-** Free any prior content in *pz and replace it with a copy of zNew.
-*/
-SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
- sqlite3DbFree(db, *pz);
- *pz = sqlite3DbStrDup(db, zNew);
-}
-
-/*
-** Call this routine to record the fact that an OOM (out-of-memory) error
-** has happened. This routine will set db->mallocFailed, and also
-** temporarily disable the lookaside memory allocator and interrupt
-** any running VDBEs.
-*/
-SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
- if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
- db->mallocFailed = 1;
- if( db->nVdbeExec>0 ){
- db->u1.isInterrupted = 1;
- }
- db->lookaside.bDisable++;
- if( db->pParse ){
- db->pParse->rc = SQLITE_NOMEM_BKPT;
- }
- }
-}
-
-/*
-** This routine reactivates the memory allocator and clears the
-** db->mallocFailed flag as necessary.
-**
-** The memory allocator is not restarted if there are running
-** VDBEs.
-*/
-SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
- if( db->mallocFailed && db->nVdbeExec==0 ){
- db->mallocFailed = 0;
- db->u1.isInterrupted = 0;
- assert( db->lookaside.bDisable>0 );
- db->lookaside.bDisable--;
- }
-}
-
-/*
-** Take actions at the end of an API call to indicate an OOM error
-*/
-static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
- sqlite3OomClear(db);
- sqlite3Error(db, SQLITE_NOMEM);
- return SQLITE_NOMEM_BKPT;
-}
-
-/*
-** 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 an OOM as occurred, then the connection error-code (the value
-** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
-*/
-SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
- /* If the db handle must hold the connection handle mutex here.
- ** Otherwise the read (and possible write) of db->mallocFailed
- ** is unsafe, as is the call to sqlite3Error().
- */
- assert( db!=0 );
- assert( sqlite3_mutex_held(db->mutex) );
- if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
- return apiOomError(db);
- }
- return rc & db->errMask;
-}
-
-/************** End of malloc.c **********************************************/
-/************** Begin file printf.c ******************************************/
-/*
-** The "printf" code that follows dates from the 1980's. It is in
-** the public domain.
-**
-**************************************************************************
-**
-** This file contains code for a set of "printf"-like routines. These
-** routines format strings much like the printf() from the standard C
-** library, though the implementation here has enhancements to support
-** SQLite.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** Conversion types fall into various categories as defined by the
-** following enumeration.
-*/
-#define etRADIX 0 /* non-decimal integer types. %x %o */
-#define etFLOAT 1 /* Floating point. %f */
-#define etEXP 2 /* Exponentional notation. %e and %E */
-#define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
-#define etSIZE 4 /* Return number of characters processed so far. %n */
-#define etSTRING 5 /* Strings. %s */
-#define etDYNSTRING 6 /* Dynamically allocated strings. %z */
-#define etPERCENT 7 /* Percent symbol. %% */
-#define etCHARX 8 /* Characters. %c */
-/* The rest are extensions, not normally found in printf() */
-#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
-#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
- NULL pointers replaced by SQL NULL. %Q */
-#define etTOKEN 11 /* a pointer to a Token structure */
-#define etSRCLIST 12 /* a pointer to a SrcList */
-#define etPOINTER 13 /* The %p conversion */
-#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
-#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
-#define etDECIMAL 16 /* %d or %u, but not %x, %o */
-
-#define etINVALID 17 /* 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
-*/
-typedef struct et_info { /* Information about each format field */
- char fmttype; /* The format field code letter */
- etByte base; /* The base for radix conversion */
- etByte flags; /* One or more of FLAG_ constants below */
- etByte type; /* Conversion paradigm */
- etByte charset; /* Offset into aDigits[] of the digits string */
- etByte prefix; /* Offset into aPrefix[] of the prefix string */
-} et_info;
-
-/*
-** Allowed values for et_info.flags
-*/
-#define FLAG_SIGNED 1 /* True if the value to convert is signed */
-#define FLAG_STRING 4 /* Allow infinite precision */
-
-
-/*
-** The following table is searched linearly, so it is good to put the
-** most frequently used conversion types first.
-*/
-static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
-static const char aPrefix[] = "-x0\000X0";
-static const et_info fmtinfo[] = {
- { 'd', 10, 1, etDECIMAL, 0, 0 },
- { 's', 0, 4, etSTRING, 0, 0 },
- { 'g', 0, 1, etGENERIC, 30, 0 },
- { 'z', 0, 4, etDYNSTRING, 0, 0 },
- { 'q', 0, 4, etSQLESCAPE, 0, 0 },
- { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
- { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
- { 'c', 0, 0, etCHARX, 0, 0 },
- { 'o', 8, 0, etRADIX, 0, 2 },
- { 'u', 10, 0, etDECIMAL, 0, 0 },
- { 'x', 16, 0, etRADIX, 16, 1 },
- { 'X', 16, 0, etRADIX, 0, 4 },
-#ifndef SQLITE_OMIT_FLOATING_POINT
- { 'f', 0, 1, etFLOAT, 0, 0 },
- { 'e', 0, 1, etEXP, 30, 0 },
- { 'E', 0, 1, etEXP, 14, 0 },
- { 'G', 0, 1, etGENERIC, 14, 0 },
-#endif
- { 'i', 10, 1, etDECIMAL, 0, 0 },
- { 'n', 0, 0, etSIZE, 0, 0 },
- { '%', 0, 0, etPERCENT, 0, 0 },
- { 'p', 16, 0, etPOINTER, 0, 1 },
-
- /* All the rest are undocumented and are for internal use only */
- { 'T', 0, 0, etTOKEN, 0, 0 },
- { 'S', 0, 0, etSRCLIST, 0, 0 },
- { 'r', 10, 1, etORDINAL, 0, 0 },
-};
-
-/* Floating point constants used for rounding */
-static const double arRound[] = {
- 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
- 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
-};
-
-/*
-** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
-** conversions will work.
-*/
-#ifndef 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(LONGDOUBLE_TYPE *val, int *cnt){
- int digit;
- LONGDOUBLE_TYPE d;
- if( (*cnt)<=0 ) return '0';
- (*cnt)--;
- digit = (int)*val;
- d = digit;
- digit += '0';
- *val = (*val - d)*10.0;
- return (char)digit;
-}
-#endif /* SQLITE_OMIT_FLOATING_POINT */
-
-/*
-** Set the StrAccum object to an error mode.
-*/
-static void setStrAccumError(StrAccum *p, u8 eError){
- assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
- p->accError = eError;
- if( p->mxAlloc ) sqlite3_str_reset(p);
- if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
-}
-
-/*
-** Extra argument values from a PrintfArguments object
-*/
-static sqlite3_int64 getIntArg(PrintfArguments *p){
- if( p->nArg<=p->nUsed ) return 0;
- return sqlite3_value_int64(p->apArg[p->nUsed++]);
-}
-static double getDoubleArg(PrintfArguments *p){
- if( p->nArg<=p->nUsed ) return 0.0;
- return sqlite3_value_double(p->apArg[p->nUsed++]);
-}
-static char *getTextArg(PrintfArguments *p){
- if( p->nArg<=p->nUsed ) return 0;
- return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
-}
-
-/*
-** Allocate memory for a temporary buffer needed for printf rendering.
-**
-** If the requested size of the temp buffer is larger than the size
-** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
-** Do the size check before the memory allocation to prevent rogue
-** SQL from requesting large allocations using the precision or width
-** field of the printf() function.
-*/
-static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
- char *z;
- if( pAccum->accError ) return 0;
- if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
- setStrAccumError(pAccum, SQLITE_TOOBIG);
- return 0;
- }
- z = sqlite3DbMallocRaw(pAccum->db, n);
- if( z==0 ){
- setStrAccumError(pAccum, SQLITE_NOMEM);
- }
- return z;
-}
-
-/*
-** On machines with a small stack size, you can redefine the
-** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
-*/
-#ifndef SQLITE_PRINT_BUF_SIZE
-# define SQLITE_PRINT_BUF_SIZE 70
-#endif
-#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
-
-/*
-** Render a string given by "fmt" into the StrAccum object.
-*/
-SQLITE_API void sqlite3_str_vappendf(
- sqlite3_str *pAccum, /* Accumulate results here */
- const char *fmt, /* Format string */
- va_list ap /* arguments */
-){
- int c; /* Next character in the format string */
- char *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_prefix; /* '+' or ' ' or 0 for prefix */
- 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; /* 1 for the "l" flag, 2 for "ll", 0 by default */
- etByte done; /* Loop termination flag */
- etByte cThousand; /* Thousands separator for %d and %u */
- etByte xtype = etINVALID; /* Conversion paradigm */
- u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
- char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
- sqlite_uint64 longvalue; /* Value for integer types */
- LONGDOUBLE_TYPE realvalue; /* Value for real types */
- const et_info *infop; /* Pointer to the appropriate info structure */
- char *zOut; /* Rendering buffer */
- int nOut; /* Size of the rendering buffer */
- char *zExtra = 0; /* Malloced memory used by some conversion */
-#ifndef SQLITE_OMIT_FLOATING_POINT
- int exp, e2; /* exponent of real numbers */
- int nsd; /* Number of significant digits returned */
- 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 */
-#endif
- PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
- char buf[etBUFSIZE]; /* Conversion buffer */
-
- /* pAccum never starts out with an empty buffer that was obtained from
- ** malloc(). This precondition is required by the mprintf("%z...")
- ** optimization. */
- assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
-
- bufpt = 0;
- if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
- pArgList = va_arg(ap, PrintfArguments*);
- bArgList = 1;
- }else{
- bArgList = 0;
- }
- for(; (c=(*fmt))!=0; ++fmt){
- if( c!='%' ){
- bufpt = (char *)fmt;
-#if HAVE_STRCHRNUL
- fmt = strchrnul(fmt, '%');
-#else
- do{ fmt++; }while( *fmt && *fmt != '%' );
-#endif
- sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
- if( *fmt==0 ) break;
- }
- if( (c=(*++fmt))==0 ){
- sqlite3_str_append(pAccum, "%", 1);
- break;
- }
- /* Find out what flags are present */
- flag_leftjustify = flag_prefix = cThousand =
- flag_alternateform = flag_altform2 = flag_zeropad = 0;
- done = 0;
- width = 0;
- flag_long = 0;
- precision = -1;
- do{
- switch( c ){
- case '-': flag_leftjustify = 1; break;
- case '+': flag_prefix = '+'; break;
- case ' ': flag_prefix = ' '; break;
- case '#': flag_alternateform = 1; break;
- case '!': flag_altform2 = 1; break;
- case '0': flag_zeropad = 1; break;
- case ',': cThousand = ','; break;
- default: done = 1; break;
- case 'l': {
- flag_long = 1;
- c = *++fmt;
- if( c=='l' ){
- c = *++fmt;
- flag_long = 2;
- }
- done = 1;
- break;
- }
- case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9': {
- unsigned wx = c - '0';
- while( (c = *++fmt)>='0' && c<='9' ){
- wx = wx*10 + c - '0';
- }
- testcase( wx>0x7fffffff );
- width = wx & 0x7fffffff;
-#ifdef SQLITE_PRINTF_PRECISION_LIMIT
- if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
- width = SQLITE_PRINTF_PRECISION_LIMIT;
- }
-#endif
- if( c!='.' && c!='l' ){
- done = 1;
- }else{
- fmt--;
- }
- break;
- }
- case '*': {
- if( bArgList ){
- width = (int)getIntArg(pArgList);
- }else{
- width = va_arg(ap,int);
- }
- if( width<0 ){
- flag_leftjustify = 1;
- width = width >= -2147483647 ? -width : 0;
- }
-#ifdef SQLITE_PRINTF_PRECISION_LIMIT
- if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
- width = SQLITE_PRINTF_PRECISION_LIMIT;
- }
-#endif
- if( (c = fmt[1])!='.' && c!='l' ){
- c = *++fmt;
- done = 1;
- }
- break;
- }
- case '.': {
- c = *++fmt;
- if( c=='*' ){
- if( bArgList ){
- precision = (int)getIntArg(pArgList);
- }else{
- precision = va_arg(ap,int);
- }
- if( precision<0 ){
- precision = precision >= -2147483647 ? -precision : -1;
- }
- c = *++fmt;
- }else{
- unsigned px = 0;
- while( c>='0' && c<='9' ){
- px = px*10 + c - '0';
- c = *++fmt;
- }
- testcase( px>0x7fffffff );
- precision = px & 0x7fffffff;
- }
-#ifdef SQLITE_PRINTF_PRECISION_LIMIT
- if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
- precision = SQLITE_PRINTF_PRECISION_LIMIT;
- }
-#endif
- if( c=='l' ){
- --fmt;
- }else{
- done = 1;
- }
- break;
- }
- }
- }while( !done && (c=(*++fmt))!=0 );
-
- /* Fetch the info entry for the field */
- infop = &fmtinfo[0];
- xtype = etINVALID;
- for(idx=0; idxtype;
- break;
- }
- }
-
- /*
- ** At this point, variables are initialized as follows:
- **
- ** flag_alternateform TRUE if a '#' is present.
- ** flag_altform2 TRUE if a '!' is present.
- ** flag_prefix '+' or ' ' or zero
- ** 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 1 for "l", 2 for "ll"
- ** 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_long = sizeof(char*)==sizeof(i64) ? 2 :
- sizeof(char*)==sizeof(long int) ? 1 : 0;
- /* Fall through into the next case */
- case etORDINAL:
- case etRADIX:
- cThousand = 0;
- /* Fall through into the next case */
- case etDECIMAL:
- if( infop->flags & FLAG_SIGNED ){
- i64 v;
- if( bArgList ){
- v = getIntArg(pArgList);
- }else if( flag_long ){
- if( flag_long==2 ){
- v = va_arg(ap,i64) ;
- }else{
- v = va_arg(ap,long int);
- }
- }else{
- v = va_arg(ap,int);
- }
- if( v<0 ){
- if( v==SMALLEST_INT64 ){
- longvalue = ((u64)1)<<63;
- }else{
- longvalue = -v;
- }
- prefix = '-';
- }else{
- longvalue = v;
- prefix = flag_prefix;
- }
- }else{
- if( bArgList ){
- longvalue = (u64)getIntArg(pArgList);
- }else if( flag_long ){
- if( flag_long==2 ){
- longvalue = va_arg(ap,u64);
- }else{
- longvalue = va_arg(ap,unsigned long int);
- }
- }else{
- longvalue = va_arg(ap,unsigned int);
- }
- prefix = 0;
- }
- if( longvalue==0 ) flag_alternateform = 0;
- if( flag_zeropad && precision=4 || (longvalue/10)%10==1 ){
- x = 0;
- }
- *(--bufpt) = zOrd[x*2+1];
- *(--bufpt) = zOrd[x*2];
- }
- {
- const char *cset = &aDigits[infop->charset];
- u8 base = infop->base;
- do{ /* Convert to ascii */
- *(--bufpt) = cset[longvalue%base];
- longvalue = longvalue/base;
- }while( longvalue>0 );
- }
- length = (int)(&zOut[nOut-1]-bufpt);
- while( precision>length ){
- *(--bufpt) = '0'; /* Zero pad */
- length++;
- }
- if( cThousand ){
- int nn = (length - 1)/3; /* Number of "," to insert */
- int ix = (length - 1)%3 + 1;
- bufpt -= nn;
- for(idx=0; nn>0; idx++){
- bufpt[idx] = bufpt[idx+nn];
- ix--;
- if( ix==0 ){
- bufpt[++idx] = cThousand;
- nn--;
- ix = 3;
- }
- }
- }
- if( prefix ) *(--bufpt) = prefix; /* Add sign */
- if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
- const char *pre;
- char x;
- pre = &aPrefix[infop->prefix];
- for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
- }
- length = (int)(&zOut[nOut-1]-bufpt);
- break;
- case etFLOAT:
- case etEXP:
- case etGENERIC:
- if( bArgList ){
- realvalue = getDoubleArg(pArgList);
- }else{
- realvalue = va_arg(ap,double);
- }
-#ifdef SQLITE_OMIT_FLOATING_POINT
- length = 0;
-#else
- if( precision<0 ) precision = 6; /* Set default precision */
- if( realvalue<0.0 ){
- realvalue = -realvalue;
- prefix = '-';
- }else{
- prefix = flag_prefix;
- }
- if( xtype==etGENERIC && precision>0 ) precision--;
- testcase( precision>0xfff );
- idx = precision & 0xfff;
- rounder = arRound[idx%10];
- while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
- if( xtype==etFLOAT ){
- double rx = (double)realvalue;
- sqlite3_uint64 u;
- int ex;
- memcpy(&u, &rx, sizeof(u));
- ex = -1023 + (int)((u>>52)&0x7ff);
- if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
- realvalue += rounder;
- }
- /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
- exp = 0;
- if( sqlite3IsNaN((double)realvalue) ){
- bufpt = "NaN";
- length = 3;
- break;
- }
- if( realvalue>0.0 ){
- LONGDOUBLE_TYPE scale = 1.0;
- while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
- while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
- while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
- realvalue /= scale;
- while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
- while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
- if( exp>350 ){
- bufpt = buf;
- buf[0] = prefix;
- memcpy(buf+(prefix!=0),"Inf",4);
- length = 3+(prefix!=0);
- break;
- }
- }
- bufpt = buf;
- /*
- ** If the field type is etGENERIC, then convert to either etEXP
- ** or etFLOAT, as appropriate.
- */
- 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 = flag_altform2;
- }
- if( xtype==etEXP ){
- e2 = 0;
- }else{
- e2 = exp;
- }
- {
- i64 szBufNeeded; /* Size of a temporary buffer needed */
- szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
- if( szBufNeeded > etBUFSIZE ){
- bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
- if( bufpt==0 ) return;
- }
- }
- zOut = bufpt;
- nsd = 16 + flag_altform2*10;
- flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
- /* The sign in front of the number */
- if( prefix ){
- *(bufpt++) = prefix;
- }
- /* Digits prior to the decimal point */
- if( e2<0 ){
- *(bufpt++) = '0';
- }else{
- for(; e2>=0; e2--){
- *(bufpt++) = et_getdigit(&realvalue,&nsd);
- }
- }
- /* The decimal point */
- if( flag_dp ){
- *(bufpt++) = '.';
- }
- /* "0" digits after the decimal point but before the first
- ** significant digit of the number */
- for(e2++; e2<0; precision--, e2++){
- assert( precision>0 );
- *(bufpt++) = '0';
- }
- /* Significant digits after the decimal point */
- while( (precision--)>0 ){
- *(bufpt++) = et_getdigit(&realvalue,&nsd);
- }
- /* Remove trailing zeros and the "." if no digits follow the "." */
- if( flag_rtz && flag_dp ){
- while( bufpt[-1]=='0' ) *(--bufpt) = 0;
- assert( bufpt>zOut );
- if( bufpt[-1]=='.' ){
- if( flag_altform2 ){
- *(bufpt++) = '0';
- }else{
- *(--bufpt) = 0;
- }
- }
- }
- /* Add the "eNNN" suffix */
- if( xtype==etEXP ){
- *(bufpt++) = aDigits[infop->charset];
- if( exp<0 ){
- *(bufpt++) = '-'; exp = -exp;
- }else{
- *(bufpt++) = '+';
- }
- if( exp>=100 ){
- *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
- exp %= 100;
- }
- *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
- *(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 = (int)(bufpt-zOut);
- bufpt = zOut;
-
- /* 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--){
- bufpt[i] = bufpt[i-nPad];
- }
- i = prefix!=0;
- while( nPad-- ) bufpt[i++] = '0';
- length = width;
- }
-#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
- break;
- case etSIZE:
- if( !bArgList ){
- *(va_arg(ap,int*)) = pAccum->nChar;
- }
- length = width = 0;
- break;
- case etPERCENT:
- buf[0] = '%';
- bufpt = buf;
- length = 1;
- break;
- case etCHARX:
- if( bArgList ){
- bufpt = getTextArg(pArgList);
- length = 1;
- if( bufpt ){
- buf[0] = c = *(bufpt++);
- if( (c&0xc0)==0xc0 ){
- while( length<4 && (bufpt[0]&0xc0)==0x80 ){
- buf[length++] = *(bufpt++);
- }
- }
- }else{
- buf[0] = 0;
- }
- }else{
- unsigned int ch = va_arg(ap,unsigned int);
- if( ch<0x00080 ){
- buf[0] = ch & 0xff;
- length = 1;
- }else if( ch<0x00800 ){
- buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
- buf[1] = 0x80 + (u8)(ch & 0x3f);
- length = 2;
- }else if( ch<0x10000 ){
- buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
- buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
- buf[2] = 0x80 + (u8)(ch & 0x3f);
- length = 3;
- }else{
- buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
- buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
- buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
- buf[3] = 0x80 + (u8)(ch & 0x3f);
- length = 4;
- }
- }
- if( precision>1 ){
- width -= precision-1;
- if( width>1 && !flag_leftjustify ){
- sqlite3_str_appendchar(pAccum, width-1, ' ');
- width = 0;
- }
- while( precision-- > 1 ){
- sqlite3_str_append(pAccum, buf, length);
- }
- }
- bufpt = buf;
- flag_altform2 = 1;
- goto adjust_width_for_utf8;
- case etSTRING:
- case etDYNSTRING:
- if( bArgList ){
- bufpt = getTextArg(pArgList);
- xtype = etSTRING;
- }else{
- bufpt = va_arg(ap,char*);
- }
- if( bufpt==0 ){
- bufpt = "";
- }else if( xtype==etDYNSTRING ){
- if( pAccum->nChar==0
- && pAccum->mxAlloc
- && width==0
- && precision<0
- && pAccum->accError==0
- ){
- /* Special optimization for sqlite3_mprintf("%z..."):
- ** Extend an existing memory allocation rather than creating
- ** a new one. */
- assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
- pAccum->zText = bufpt;
- pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
- pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
- pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
- length = 0;
- break;
- }
- zExtra = bufpt;
- }
- if( precision>=0 ){
- if( flag_altform2 ){
- /* Set length to the number of bytes needed in order to display
- ** precision characters */
- unsigned char *z = (unsigned char*)bufpt;
- while( precision-- > 0 && z[0] ){
- SQLITE_SKIP_UTF8(z);
- }
- length = (int)(z - (unsigned char*)bufpt);
- }else{
- for(length=0; length0 ){
- /* Adjust width to account for extra bytes in UTF-8 characters */
- int ii = length - 1;
- while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
- }
- break;
- case etSQLESCAPE: /* %q: Escape ' characters */
- case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
- case etSQLESCAPE3: { /* %w: Escape " characters */
- int i, j, k, n, isnull;
- int needQuote;
- char ch;
- char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
- char *escarg;
-
- if( bArgList ){
- escarg = getTextArg(pArgList);
- }else{
- escarg = va_arg(ap,char*);
- }
- isnull = escarg==0;
- if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
- /* For %q, %Q, and %w, the precision is the number of byte (or
- ** characters if the ! flags is present) to use from the input.
- ** Because of the extra quoting characters inserted, the number
- ** of output characters may be larger than the precision.
- */
- k = precision;
- for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
- if( ch==q ) n++;
- if( flag_altform2 && (ch&0xc0)==0xc0 ){
- while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
- }
- }
- needQuote = !isnull && xtype==etSQLESCAPE2;
- n += i + 3;
- if( n>etBUFSIZE ){
- bufpt = zExtra = printfTempBuf(pAccum, n);
- if( bufpt==0 ) return;
- }else{
- bufpt = buf;
- }
- j = 0;
- if( needQuote ) bufpt[j++] = q;
- k = i;
- for(i=0; iprintfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
- pToken = va_arg(ap, Token*);
- assert( bArgList==0 );
- if( pToken && pToken->n ){
- sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
- }
- length = width = 0;
- break;
- }
- case etSRCLIST: {
- SrcList *pSrc;
- int k;
- struct SrcList_item *pItem;
- if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
- pSrc = va_arg(ap, SrcList*);
- k = va_arg(ap, int);
- pItem = &pSrc->a[k];
- assert( bArgList==0 );
- assert( k>=0 && knSrc );
- if( pItem->zDatabase ){
- sqlite3_str_appendall(pAccum, pItem->zDatabase);
- sqlite3_str_append(pAccum, ".", 1);
- }
- sqlite3_str_appendall(pAccum, pItem->zName);
- length = width = 0;
- break;
- }
- default: {
- 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. Both length and width are in bytes, not characters,
- ** at this point. If the "!" flag was present on string conversions
- ** indicating that width and precision should be expressed in characters,
- ** then the values have been translated prior to reaching this point.
- */
- width -= length;
- if( width>0 ){
- if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
- sqlite3_str_append(pAccum, bufpt, length);
- if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
- }else{
- sqlite3_str_append(pAccum, bufpt, length);
- }
-
- if( zExtra ){
- sqlite3DbFree(pAccum->db, zExtra);
- zExtra = 0;
- }
- }/* End for loop over the format string */
-} /* End of function */
-
-/*
-** Enlarge the memory allocation on a StrAccum object so that it is
-** able to accept at least N more bytes of text.
-**
-** Return the number of bytes of text that StrAccum is able to accept
-** after the attempted enlargement. The value returned might be zero.
-*/
-static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
- char *zNew;
- assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
- if( p->accError ){
- testcase(p->accError==SQLITE_TOOBIG);
- testcase(p->accError==SQLITE_NOMEM);
- return 0;
- }
- if( p->mxAlloc==0 ){
- setStrAccumError(p, SQLITE_TOOBIG);
- return p->nAlloc - p->nChar - 1;
- }else{
- char *zOld = isMalloced(p) ? p->zText : 0;
- i64 szNew = p->nChar;
- szNew += N + 1;
- if( szNew+p->nChar<=p->mxAlloc ){
- /* Force exponential buffer size growth as long as it does not overflow,
- ** to avoid having to call this routine too often */
- szNew += p->nChar;
- }
- if( szNew > p->mxAlloc ){
- sqlite3_str_reset(p);
- setStrAccumError(p, SQLITE_TOOBIG);
- return 0;
- }else{
- p->nAlloc = (int)szNew;
- }
- if( p->db ){
- zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
- }else{
- zNew = sqlite3_realloc64(zOld, p->nAlloc);
- }
- if( zNew ){
- assert( p->zText!=0 || p->nChar==0 );
- if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
- p->zText = zNew;
- p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
- p->printfFlags |= SQLITE_PRINTF_MALLOCED;
- }else{
- sqlite3_str_reset(p);
- setStrAccumError(p, SQLITE_NOMEM);
- return 0;
- }
- }
- return N;
-}
-
-/*
-** Append N copies of character c to the given string buffer.
-*/
-SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
- testcase( p->nChar + (i64)N > 0x7fffffff );
- if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
- return;
- }
- while( (N--)>0 ) p->zText[p->nChar++] = c;
-}
-
-/*
-** The StrAccum "p" is not large enough to accept N new bytes of z[].
-** So enlarge if first, then do the append.
-**
-** This is a helper routine to sqlite3_str_append() that does special-case
-** work (enlarging the buffer) using tail recursion, so that the
-** sqlite3_str_append() routine can use fast calling semantics.
-*/
-static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
- N = sqlite3StrAccumEnlarge(p, N);
- if( N>0 ){
- memcpy(&p->zText[p->nChar], z, N);
- p->nChar += N;
- }
-}
-
-/*
-** Append N bytes of text from z to the StrAccum object. Increase the
-** size of the memory allocation for StrAccum if necessary.
-*/
-SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
- assert( z!=0 || N==0 );
- assert( p->zText!=0 || p->nChar==0 || p->accError );
- assert( N>=0 );
- assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
- if( p->nChar+N >= p->nAlloc ){
- enlargeAndAppend(p,z,N);
- }else if( N ){
- assert( p->zText );
- p->nChar += N;
- memcpy(&p->zText[p->nChar-N], z, N);
- }
-}
-
-/*
-** Append the complete text of zero-terminated string z[] to the p string.
-*/
-SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
- sqlite3_str_append(p, z, sqlite3Strlen30(z));
-}
-
-
-/*
-** 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 SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
- char *zText;
- assert( p->mxAlloc>0 && !isMalloced(p) );
- zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
- if( zText ){
- memcpy(zText, p->zText, p->nChar+1);
- p->printfFlags |= SQLITE_PRINTF_MALLOCED;
- }else{
- setStrAccumError(p, SQLITE_NOMEM);
- }
- p->zText = zText;
- return zText;
-}
-SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
- if( p->zText ){
- p->zText[p->nChar] = 0;
- if( p->mxAlloc>0 && !isMalloced(p) ){
- return strAccumFinishRealloc(p);
- }
- }
- return p->zText;
-}
-
-/*
-** This singleton is an sqlite3_str object that is returned if
-** sqlite3_malloc() fails to provide space for a real one. This
-** sqlite3_str object accepts no new text and always returns
-** an SQLITE_NOMEM error.
-*/
-static sqlite3_str sqlite3OomStr = {
- 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
-};
-
-/* Finalize a string created using sqlite3_str_new().
-*/
-SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
- char *z;
- if( p!=0 && p!=&sqlite3OomStr ){
- z = sqlite3StrAccumFinish(p);
- sqlite3_free(p);
- }else{
- z = 0;
- }
- return z;
-}
-
-/* Return any error code associated with p */
-SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
- return p ? p->accError : SQLITE_NOMEM;
-}
-
-/* Return the current length of p in bytes */
-SQLITE_API int sqlite3_str_length(sqlite3_str *p){
- return p ? p->nChar : 0;
-}
-
-/* Return the current value for p */
-SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
- if( p==0 || p->nChar==0 ) return 0;
- p->zText[p->nChar] = 0;
- return p->zText;
-}
-
-/*
-** Reset an StrAccum string. Reclaim all malloced memory.
-*/
-SQLITE_API void sqlite3_str_reset(StrAccum *p){
- if( isMalloced(p) ){
- sqlite3DbFree(p->db, p->zText);
- p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
- }
- p->nAlloc = 0;
- p->nChar = 0;
- p->zText = 0;
-}
-
-/*
-** Initialize a string accumulator.
-**
-** p: The accumulator to be initialized.
-** db: Pointer to a database connection. May be NULL. Lookaside
-** memory is used if not NULL. db->mallocFailed is set appropriately
-** when not NULL.
-** zBase: An initial buffer. May be NULL in which case the initial buffer
-** is malloced.
-** n: Size of zBase in bytes. If total space requirements never exceed
-** n then no memory allocations ever occur.
-** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
-** allocations will ever occur.
-*/
-SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
- p->zText = zBase;
- p->db = db;
- p->nAlloc = n;
- p->mxAlloc = mx;
- p->nChar = 0;
- p->accError = 0;
- p->printfFlags = 0;
-}
-
-/* Allocate and initialize a new dynamic string object */
-SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
- sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
- if( p ){
- sqlite3StrAccumInit(p, 0, 0, 0,
- db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
- }else{
- p = &sqlite3OomStr;
- }
- return p;
-}
-
-/*
-** Print into memory obtained from sqliteMalloc(). Use the internal
-** %-conversion extensions.
-*/
-SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
- char *z;
- char zBase[SQLITE_PRINT_BUF_SIZE];
- StrAccum acc;
- assert( db!=0 );
- sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
- db->aLimit[SQLITE_LIMIT_LENGTH]);
- acc.printfFlags = SQLITE_PRINTF_INTERNAL;
- sqlite3_str_vappendf(&acc, zFormat, ap);
- z = sqlite3StrAccumFinish(&acc);
- if( acc.accError==SQLITE_NOMEM ){
- sqlite3OomFault(db);
- }
- return z;
-}
-
-/*
-** Print into memory obtained from sqliteMalloc(). Use the internal
-** %-conversion extensions.
-*/
-SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
- va_list ap;
- char *z;
- va_start(ap, zFormat);
- z = sqlite3VMPrintf(db, zFormat, ap);
- va_end(ap);
- return z;
-}
-
-/*
-** Print into memory obtained from sqlite3_malloc(). Omit the internal
-** %-conversion extensions.
-*/
-SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
- char *z;
- char zBase[SQLITE_PRINT_BUF_SIZE];
- StrAccum acc;
-
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( zFormat==0 ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
- sqlite3_str_vappendf(&acc, zFormat, ap);
- z = sqlite3StrAccumFinish(&acc);
- return z;
-}
-
-/*
-** Print into memory obtained from sqlite3_malloc()(). Omit the internal
-** %-conversion extensions.
-*/
-SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
- va_list ap;
- char *z;
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- va_start(ap, zFormat);
- z = sqlite3_vmprintf(zFormat, ap);
- va_end(ap);
- return z;
-}
-
-/*
-** sqlite3_snprintf() works like snprintf() except that it ignores the
-** current locale settings. This is important for SQLite because we
-** are not able to use a "," as the decimal point in place of "." as
-** specified by some locales.
-**
-** 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.
-*/
-SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
- StrAccum acc;
- if( n<=0 ) return zBuf;
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( zBuf==0 || zFormat==0 ) {
- (void)SQLITE_MISUSE_BKPT;
- if( zBuf ) zBuf[0] = 0;
- return zBuf;
- }
-#endif
- sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
- sqlite3_str_vappendf(&acc, zFormat, ap);
- zBuf[acc.nChar] = 0;
- return zBuf;
-}
-SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
- char *z;
- va_list ap;
- va_start(ap,zFormat);
- z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
- va_end(ap);
- return 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.
-**
-** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
-** certain format characters (%q) or for very large precisions or widths.
-** Care must be taken that any sqlite3_log() calls that occur while the
-** memory mutex is held do not use these mechanisms.
-*/
-static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
- StrAccum acc; /* String accumulator */
- char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
-
- sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
- sqlite3_str_vappendf(&acc, zFormat, ap);
- sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
- sqlite3StrAccumFinish(&acc));
-}
-
-/*
-** Format and write a message to the log if logging is enabled.
-*/
-SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
- va_list ap; /* Vararg list */
- if( sqlite3GlobalConfig.xLog ){
- va_start(ap, zFormat);
- renderLogMsg(iErrCode, zFormat, ap);
- va_end(ap);
- }
-}
-
-#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_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.
-*/
-SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
- va_list ap;
- StrAccum acc;
- char zBuf[500];
- sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
- va_start(ap,zFormat);
- sqlite3_str_vappendf(&acc, zFormat, ap);
- va_end(ap);
- sqlite3StrAccumFinish(&acc);
-#ifdef SQLITE_OS_TRACE_PROC
- {
- extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
- SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
- }
-#else
- fprintf(stdout,"%s", zBuf);
- fflush(stdout);
-#endif
-}
-#endif
-
-
-/*
-** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
-** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
-*/
-SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
- va_list ap;
- va_start(ap,zFormat);
- sqlite3_str_vappendf(p, zFormat, ap);
- va_end(ap);
-}
-
-/************** End of printf.c **********************************************/
-/************** Begin file treeview.c ****************************************/
-/*
-** 2015-06-08
-**
-** 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 to implement the TreeView debugging routines.
-** These routines print a parse tree to standard output for debugging and
-** analysis.
-**
-** The interfaces in this file is only available when compiling
-** with SQLITE_DEBUG.
-*/
-/* #include "sqliteInt.h" */
-#ifdef SQLITE_DEBUG
-
-/*
-** Add a new subitem to the tree. The moreToFollow flag indicates that this
-** is not the last item in the tree.
-*/
-static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
- if( p==0 ){
- p = sqlite3_malloc64( sizeof(*p) );
- if( p==0 ) return 0;
- memset(p, 0, sizeof(*p));
- }else{
- p->iLevel++;
- }
- assert( moreToFollow==0 || moreToFollow==1 );
- if( p->iLevelbLine) ) p->bLine[p->iLevel] = moreToFollow;
- return p;
-}
-
-/*
-** Finished with one layer of the tree
-*/
-static void sqlite3TreeViewPop(TreeView *p){
- if( p==0 ) return;
- p->iLevel--;
- if( p->iLevel<0 ) sqlite3_free(p);
-}
-
-/*
-** Generate a single line of output for the tree, with a prefix that contains
-** all the appropriate tree lines
-*/
-static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
- va_list ap;
- int i;
- StrAccum acc;
- char zBuf[500];
- sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
- if( p ){
- for(i=0; iiLevel && ibLine)-1; i++){
- sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
- }
- sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
- }
- if( zFormat!=0 ){
- va_start(ap, zFormat);
- sqlite3_str_vappendf(&acc, zFormat, ap);
- va_end(ap);
- assert( acc.nChar>0 );
- sqlite3_str_append(&acc, "\n", 1);
- }
- sqlite3StrAccumFinish(&acc);
- fprintf(stdout,"%s", zBuf);
- fflush(stdout);
-}
-
-/*
-** Shorthand for starting a new tree item that consists of a single label
-*/
-static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
- p = sqlite3TreeViewPush(p, moreFollows);
- sqlite3TreeViewLine(p, "%s", zLabel);
-}
-
-/*
-** Generate a human-readable description of a WITH clause.
-*/
-SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
- int i;
- if( pWith==0 ) return;
- if( pWith->nCte==0 ) return;
- if( pWith->pOuter ){
- sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
- }else{
- sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
- }
- if( pWith->nCte>0 ){
- pView = sqlite3TreeViewPush(pView, 1);
- for(i=0; inCte; i++){
- StrAccum x;
- char zLine[1000];
- const struct Cte *pCte = &pWith->a[i];
- sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
- sqlite3_str_appendf(&x, "%s", pCte->zName);
- if( pCte->pCols && pCte->pCols->nExpr>0 ){
- char cSep = '(';
- int j;
- for(j=0; jpCols->nExpr; j++){
- sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
- cSep = ',';
- }
- sqlite3_str_appendf(&x, ")");
- }
- sqlite3_str_appendf(&x, " AS");
- sqlite3StrAccumFinish(&x);
- sqlite3TreeViewItem(pView, zLine, inCte-1);
- sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
- sqlite3TreeViewPop(pView);
- }
- sqlite3TreeViewPop(pView);
- }
-}
-
-/*
-** Generate a human-readable description of a SrcList object.
-*/
-SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
- int i;
- for(i=0; inSrc; i++){
- const struct SrcList_item *pItem = &pSrc->a[i];
- StrAccum x;
- char zLine[100];
- sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
- sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
- if( pItem->zDatabase ){
- sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
- }else if( pItem->zName ){
- sqlite3_str_appendf(&x, " %s", pItem->zName);
- }
- if( pItem->pTab ){
- sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p",
- pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab);
- }
- if( pItem->zAlias ){
- sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
- }
- if( pItem->fg.jointype & JT_LEFT ){
- sqlite3_str_appendf(&x, " LEFT-JOIN");
- }
- sqlite3StrAccumFinish(&x);
- sqlite3TreeViewItem(pView, zLine, inSrc-1);
- if( pItem->pSelect ){
- sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
- }
- if( pItem->fg.isTabFunc ){
- sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
- }
- sqlite3TreeViewPop(pView);
- }
-}
-
-/*
-** Generate a human-readable description of a Select object.
-*/
-SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
- int n = 0;
- int cnt = 0;
- if( p==0 ){
- sqlite3TreeViewLine(pView, "nil-SELECT");
- return;
- }
- pView = sqlite3TreeViewPush(pView, moreToFollow);
- if( p->pWith ){
- sqlite3TreeViewWith(pView, p->pWith, 1);
- cnt = 1;
- sqlite3TreeViewPush(pView, 1);
- }
- do{
- sqlite3TreeViewLine(pView,
- "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
- ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
- ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
- p->selId, p, p->selFlags,
- (int)p->nSelectRow
- );
- if( cnt++ ) sqlite3TreeViewPop(pView);
- if( p->pPrior ){
- n = 1000;
- }else{
- n = 0;
- if( p->pSrc && p->pSrc->nSrc ) n++;
- if( p->pWhere ) n++;
- if( p->pGroupBy ) n++;
- if( p->pHaving ) n++;
- if( p->pOrderBy ) n++;
- if( p->pLimit ) n++;
-#ifndef SQLITE_OMIT_WINDOWFUNC
- if( p->pWin ) n++;
- if( p->pWinDefn ) n++;
-#endif
- }
- sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
-#ifndef SQLITE_OMIT_WINDOWFUNC
- if( p->pWin ){
- Window *pX;
- pView = sqlite3TreeViewPush(pView, (n--)>0);
- sqlite3TreeViewLine(pView, "window-functions");
- for(pX=p->pWin; pX; pX=pX->pNextWin){
- sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
- }
- sqlite3TreeViewPop(pView);
- }
-#endif
- if( p->pSrc && p->pSrc->nSrc ){
- pView = sqlite3TreeViewPush(pView, (n--)>0);
- sqlite3TreeViewLine(pView, "FROM");
- sqlite3TreeViewSrcList(pView, p->pSrc);
- sqlite3TreeViewPop(pView);
- }
- if( p->pWhere ){
- sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
- sqlite3TreeViewExpr(pView, p->pWhere, 0);
- sqlite3TreeViewPop(pView);
- }
- if( p->pGroupBy ){
- sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
- }
- if( p->pHaving ){
- sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
- sqlite3TreeViewExpr(pView, p->pHaving, 0);
- sqlite3TreeViewPop(pView);
- }
-#ifndef SQLITE_OMIT_WINDOWFUNC
- if( p->pWinDefn ){
- Window *pX;
- sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
- for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
- sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
- }
- sqlite3TreeViewPop(pView);
- }
-#endif
- if( p->pOrderBy ){
- sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
- }
- if( p->pLimit ){
- sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
- sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
- if( p->pLimit->pRight ){
- sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
- sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
- sqlite3TreeViewPop(pView);
- }
- sqlite3TreeViewPop(pView);
- }
- if( p->pPrior ){
- const char *zOp = "UNION";
- switch( p->op ){
- case TK_ALL: zOp = "UNION ALL"; break;
- case TK_INTERSECT: zOp = "INTERSECT"; break;
- case TK_EXCEPT: zOp = "EXCEPT"; break;
- }
- sqlite3TreeViewItem(pView, zOp, 1);
- }
- p = p->pPrior;
- }while( p!=0 );
- sqlite3TreeViewPop(pView);
-}
-
-#ifndef SQLITE_OMIT_WINDOWFUNC
-/*
-** Generate a description of starting or stopping bounds
-*/
-SQLITE_PRIVATE void sqlite3TreeViewBound(
- TreeView *pView, /* View context */
- u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
- Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
- u8 moreToFollow /* True if more to follow */
-){
- switch( eBound ){
- case TK_UNBOUNDED: {
- sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
- sqlite3TreeViewPop(pView);
- break;
- }
- case TK_CURRENT: {
- sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
- sqlite3TreeViewPop(pView);
- break;
- }
- case TK_PRECEDING: {
- sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
- sqlite3TreeViewExpr(pView, pExpr, 0);
- sqlite3TreeViewPop(pView);
- break;
- }
- case TK_FOLLOWING: {
- sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
- sqlite3TreeViewExpr(pView, pExpr, 0);
- sqlite3TreeViewPop(pView);
- break;
- }
- }
-}
-#endif /* SQLITE_OMIT_WINDOWFUNC */
-
-#ifndef SQLITE_OMIT_WINDOWFUNC
-/*
-** Generate a human-readable explanation for a Window object
-*/
-SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
- int nElement = 0;
- if( pWin->pFilter ){
- sqlite3TreeViewItem(pView, "FILTER", 1);
- sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
- sqlite3TreeViewPop(pView);
- }
- pView = sqlite3TreeViewPush(pView, more);
- if( pWin->zName ){
- sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
- }else{
- sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
- }
- if( pWin->zBase ) nElement++;
- if( pWin->pOrderBy ) nElement++;
- if( pWin->eFrmType ) nElement++;
- if( pWin->eExclude ) nElement++;
- if( pWin->zBase ){
- sqlite3TreeViewPush(pView, (--nElement)>0);
- sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
- sqlite3TreeViewPop(pView);
- }
- if( pWin->pPartition ){
- sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
- }
- if( pWin->pOrderBy ){
- sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
- }
- if( pWin->eFrmType ){
- char zBuf[30];
- const char *zFrmType = "ROWS";
- if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
- if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
- sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
- pWin->bImplicitFrame ? " (implied)" : "");
- sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
- sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
- sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
- sqlite3TreeViewPop(pView);
- }
- if( pWin->eExclude ){
- char zBuf[30];
- const char *zExclude;
- switch( pWin->eExclude ){
- case TK_NO: zExclude = "NO OTHERS"; break;
- case TK_CURRENT: zExclude = "CURRENT ROW"; break;
- case TK_GROUP: zExclude = "GROUP"; break;
- case TK_TIES: zExclude = "TIES"; break;
- default:
- sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
- zExclude = zBuf;
- break;
- }
- sqlite3TreeViewPush(pView, 0);
- sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
- sqlite3TreeViewPop(pView);
- }
- sqlite3TreeViewPop(pView);
-}
-#endif /* SQLITE_OMIT_WINDOWFUNC */
-
-#ifndef SQLITE_OMIT_WINDOWFUNC
-/*
-** Generate a human-readable explanation for a Window Function object
-*/
-SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
- pView = sqlite3TreeViewPush(pView, more);
- sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
- pWin->pFunc->zName, pWin->pFunc->nArg);
- sqlite3TreeViewWindow(pView, pWin, 0);
- sqlite3TreeViewPop(pView);
-}
-#endif /* SQLITE_OMIT_WINDOWFUNC */
-
-/*
-** Generate a human-readable explanation of an expression tree.
-*/
-SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
- const char *zBinOp = 0; /* Binary operator */
- const char *zUniOp = 0; /* Unary operator */
- char zFlgs[60];
- pView = sqlite3TreeViewPush(pView, moreToFollow);
- if( pExpr==0 ){
- sqlite3TreeViewLine(pView, "nil");
- sqlite3TreeViewPop(pView);
- return;
- }
- if( pExpr->flags ){
- if( ExprHasProperty(pExpr, EP_FromJoin) ){
- sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
- pExpr->flags, pExpr->iRightJoinTable);
- }else{
- sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
- }
- }else{
- zFlgs[0] = 0;
- }
- switch( pExpr->op ){
- case TK_AGG_COLUMN: {
- sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
- pExpr->iTable, pExpr->iColumn, zFlgs);
- break;
- }
- case TK_COLUMN: {
- if( pExpr->iTable<0 ){
- /* This only happens when coding check constraints */
- sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
- }else{
- sqlite3TreeViewLine(pView, "{%d:%d}%s",
- pExpr->iTable, pExpr->iColumn, zFlgs);
- }
- if( ExprHasProperty(pExpr, EP_FixedCol) ){
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- }
- break;
- }
- case TK_INTEGER: {
- if( pExpr->flags & EP_IntValue ){
- sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
- }else{
- sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
- }
- break;
- }
-#ifndef SQLITE_OMIT_FLOATING_POINT
- case TK_FLOAT: {
- sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
- break;
- }
-#endif
- case TK_STRING: {
- sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
- break;
- }
- case TK_NULL: {
- sqlite3TreeViewLine(pView,"NULL");
- break;
- }
- case TK_TRUEFALSE: {
- sqlite3TreeViewLine(pView,
- sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
- break;
- }
-#ifndef SQLITE_OMIT_BLOB_LITERAL
- case TK_BLOB: {
- sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
- break;
- }
-#endif
- case TK_VARIABLE: {
- sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
- pExpr->u.zToken, pExpr->iColumn);
- break;
- }
- case TK_REGISTER: {
- sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
- break;
- }
- case TK_ID: {
- sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
- break;
- }
-#ifndef SQLITE_OMIT_CAST
- case TK_CAST: {
- /* Expressions of the form: CAST(pLeft AS token) */
- sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- break;
- }
-#endif /* SQLITE_OMIT_CAST */
- case TK_LT: zBinOp = "LT"; break;
- case TK_LE: zBinOp = "LE"; break;
- case TK_GT: zBinOp = "GT"; break;
- case TK_GE: zBinOp = "GE"; break;
- case TK_NE: zBinOp = "NE"; break;
- case TK_EQ: zBinOp = "EQ"; break;
- case TK_IS: zBinOp = "IS"; break;
- case TK_ISNOT: zBinOp = "ISNOT"; break;
- case TK_AND: zBinOp = "AND"; break;
- case TK_OR: zBinOp = "OR"; break;
- case TK_PLUS: zBinOp = "ADD"; break;
- case TK_STAR: zBinOp = "MUL"; break;
- case TK_MINUS: zBinOp = "SUB"; break;
- case TK_REM: zBinOp = "REM"; break;
- case TK_BITAND: zBinOp = "BITAND"; break;
- case TK_BITOR: zBinOp = "BITOR"; break;
- case TK_SLASH: zBinOp = "DIV"; break;
- case TK_LSHIFT: zBinOp = "LSHIFT"; break;
- case TK_RSHIFT: zBinOp = "RSHIFT"; break;
- case TK_CONCAT: zBinOp = "CONCAT"; break;
- case TK_DOT: zBinOp = "DOT"; break;
-
- case TK_UMINUS: zUniOp = "UMINUS"; break;
- case TK_UPLUS: zUniOp = "UPLUS"; break;
- case TK_BITNOT: zUniOp = "BITNOT"; break;
- case TK_NOT: zUniOp = "NOT"; break;
- case TK_ISNULL: zUniOp = "ISNULL"; break;
- case TK_NOTNULL: zUniOp = "NOTNULL"; break;
-
- case TK_TRUTH: {
- int x;
- const char *azOp[] = {
- "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
- };
- assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
- assert( pExpr->pRight );
- assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
- x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
- zUniOp = azOp[x];
- break;
- }
-
- case TK_SPAN: {
- sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- break;
- }
-
- case TK_COLLATE: {
- sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- break;
- }
-
- case TK_AGG_FUNCTION:
- case TK_FUNCTION: {
- ExprList *pFarg; /* List of function arguments */
- Window *pWin;
- if( ExprHasProperty(pExpr, EP_TokenOnly) ){
- pFarg = 0;
- pWin = 0;
- }else{
- pFarg = pExpr->x.pList;
-#ifndef SQLITE_OMIT_WINDOWFUNC
- pWin = pExpr->y.pWin;
-#else
- pWin = 0;
-#endif
- }
- if( pExpr->op==TK_AGG_FUNCTION ){
- sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
- pExpr->op2, pExpr->u.zToken);
- }else{
- sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
- }
- if( pFarg ){
- sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
- }
-#ifndef SQLITE_OMIT_WINDOWFUNC
- if( pWin ){
- sqlite3TreeViewWindow(pView, pWin, 0);
- }
-#endif
- break;
- }
-#ifndef SQLITE_OMIT_SUBQUERY
- case TK_EXISTS: {
- sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
- sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
- break;
- }
- case TK_SELECT: {
- sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
- sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
- break;
- }
- case TK_IN: {
- sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
- if( ExprHasProperty(pExpr, EP_xIsSelect) ){
- sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
- }else{
- sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
- }
- 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->pList->a[0].pExpr.
- ** Z is stored in pExpr->pList->a[1].pExpr.
- */
- case TK_BETWEEN: {
- Expr *pX = pExpr->pLeft;
- Expr *pY = pExpr->x.pList->a[0].pExpr;
- Expr *pZ = pExpr->x.pList->a[1].pExpr;
- sqlite3TreeViewLine(pView, "BETWEEN");
- sqlite3TreeViewExpr(pView, pX, 1);
- sqlite3TreeViewExpr(pView, pY, 1);
- sqlite3TreeViewExpr(pView, pZ, 0);
- 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.
- */
- sqlite3TreeViewLine(pView, "%s(%d)",
- pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
- break;
- }
- case TK_CASE: {
- sqlite3TreeViewLine(pView, "CASE");
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
- sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
- break;
- }
-#ifndef SQLITE_OMIT_TRIGGER
- case TK_RAISE: {
- const char *zType = "unk";
- switch( pExpr->affinity ){
- case OE_Rollback: zType = "rollback"; break;
- case OE_Abort: zType = "abort"; break;
- case OE_Fail: zType = "fail"; break;
- case OE_Ignore: zType = "ignore"; break;
- }
- sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
- break;
- }
-#endif
- case TK_MATCH: {
- sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
- pExpr->iTable, pExpr->iColumn, zFlgs);
- sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
- break;
- }
- case TK_VECTOR: {
- sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
- break;
- }
- case TK_SELECT_COLUMN: {
- sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
- sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
- break;
- }
- case TK_IF_NULL_ROW: {
- sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- break;
- }
- default: {
- sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
- break;
- }
- }
- if( zBinOp ){
- sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
- sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
- }else if( zUniOp ){
- sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
- sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
- }
- sqlite3TreeViewPop(pView);
-}
-
-
-/*
-** Generate a human-readable explanation of an expression list.
-*/
-SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
- TreeView *pView,
- const ExprList *pList,
- const char *zLabel
-){
- if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
- if( pList==0 ){
- sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
- }else{
- int i;
- sqlite3TreeViewLine(pView, "%s", zLabel);
- for(i=0; inExpr; i++){
- int j = pList->a[i].u.x.iOrderByCol;
- char *zName = pList->a[i].zName;
- int moreToFollow = inExpr - 1;
- if( j || zName ){
- sqlite3TreeViewPush(pView, moreToFollow);
- moreToFollow = 0;
- sqlite3TreeViewLine(pView, 0);
- if( zName ){
- fprintf(stdout, "AS %s ", zName);
- }
- if( j ){
- fprintf(stdout, "iOrderByCol=%d", j);
- }
- fprintf(stdout, "\n");
- fflush(stdout);
- }
- sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
- if( j || zName ){
- sqlite3TreeViewPop(pView);
- }
- }
- }
-}
-SQLITE_PRIVATE void sqlite3TreeViewExprList(
- TreeView *pView,
- const ExprList *pList,
- u8 moreToFollow,
- const char *zLabel
-){
- pView = sqlite3TreeViewPush(pView, moreToFollow);
- sqlite3TreeViewBareExprList(pView, pList, zLabel);
- sqlite3TreeViewPop(pView);
-}
-
-#endif /* SQLITE_DEBUG */
-
-/************** End of treeview.c ********************************************/
-/************** Begin file random.c ******************************************/
-/*
-** 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.
-*/
-/* #include "sqliteInt.h" */
-
-
-/* All threads share a single random number generator.
-** This structure is the current state of the generator.
-*/
-static SQLITE_WSD struct sqlite3PrngType {
- unsigned char isInit; /* True if initialized */
- unsigned char i, j; /* State variables */
- unsigned char s[256]; /* State variables */
-} sqlite3Prng;
-
-/*
-** Return N random bytes.
-*/
-SQLITE_API void sqlite3_randomness(int N, void *pBuf){
- unsigned char t;
- unsigned char *zBuf = pBuf;
-
- /* 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.
- */
-#ifdef SQLITE_OMIT_WSD
- struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
-# define wsdPrng p[0]
-#else
-# define wsdPrng sqlite3Prng
-#endif
-
-#if SQLITE_THREADSAFE
- sqlite3_mutex *mutex;
-#endif
-
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return;
-#endif
-
-#if SQLITE_THREADSAFE
- mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
-#endif
-
- sqlite3_mutex_enter(mutex);
- if( N<=0 || pBuf==0 ){
- wsdPrng.isInit = 0;
- sqlite3_mutex_leave(mutex);
- return;
- }
-
- /* 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;
- char k[256];
- wsdPrng.j = 0;
- wsdPrng.i = 0;
- sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
- for(i=0; i<256; i++){
- wsdPrng.s[i] = (u8)i;
- }
- for(i=0; i<256; i++){
- 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 = 1;
- }
-
- assert( N>0 );
- do{
- wsdPrng.i++;
- t = wsdPrng.s[wsdPrng.i];
- wsdPrng.j += t;
- wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
- wsdPrng.s[wsdPrng.j] = t;
- t += wsdPrng.s[wsdPrng.i];
- *(zBuf++) = wsdPrng.s[t];
- }while( --N );
- sqlite3_mutex_leave(mutex);
-}
-
-#ifndef SQLITE_UNTESTABLE
-/*
-** 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 SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
-SQLITE_PRIVATE void sqlite3PrngSaveState(void){
- memcpy(
- &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
- &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
- sizeof(sqlite3Prng)
- );
-}
-SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
- memcpy(
- &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
- &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
- sizeof(sqlite3Prng)
- );
-}
-#endif /* SQLITE_UNTESTABLE */
-
-/************** End of random.c **********************************************/
-/************** Begin file threads.c *****************************************/
-/*
-** 2012 July 21
-**
-** 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 presents a simple cross-platform threading interface for
-** use internally by SQLite.
-**
-** A "thread" can be created using sqlite3ThreadCreate(). This thread
-** runs independently of its creator until it is joined using
-** sqlite3ThreadJoin(), at which point it terminates.
-**
-** Threads do not have to be real. It could be that the work of the
-** "thread" is done by the main thread at either the sqlite3ThreadCreate()
-** or sqlite3ThreadJoin() call. This is, in fact, what happens in
-** single threaded systems. Nothing in SQLite requires multiple threads.
-** This interface exists so that applications that want to take advantage
-** of multiple cores can do so, while also allowing applications to stay
-** single-threaded if desired.
-*/
-/* #include "sqliteInt.h" */
-#if SQLITE_OS_WIN
-/* # include "os_win.h" */
-#endif
-
-#if SQLITE_MAX_WORKER_THREADS>0
-
-/********************************* Unix Pthreads ****************************/
-#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
-
-#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
-/* #include */
-
-/* A running thread */
-struct SQLiteThread {
- pthread_t tid; /* Thread ID */
- int done; /* Set to true when thread finishes */
- void *pOut; /* Result returned by the thread */
- void *(*xTask)(void*); /* The thread routine */
- void *pIn; /* Argument to the thread */
-};
-
-/* Create a new thread */
-SQLITE_PRIVATE int sqlite3ThreadCreate(
- SQLiteThread **ppThread, /* OUT: Write the thread object here */
- void *(*xTask)(void*), /* Routine to run in a separate thread */
- void *pIn /* Argument passed into xTask() */
-){
- SQLiteThread *p;
- int rc;
-
- assert( ppThread!=0 );
- assert( xTask!=0 );
- /* This routine is never used in single-threaded mode */
- assert( sqlite3GlobalConfig.bCoreMutex!=0 );
-
- *ppThread = 0;
- p = sqlite3Malloc(sizeof(*p));
- if( p==0 ) return SQLITE_NOMEM_BKPT;
- memset(p, 0, sizeof(*p));
- p->xTask = xTask;
- p->pIn = pIn;
- /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
- ** function that returns SQLITE_ERROR when passed the argument 200, that
- ** forces worker threads to run sequentially and deterministically
- ** for testing purposes. */
- if( sqlite3FaultSim(200) ){
- rc = 1;
- }else{
- rc = pthread_create(&p->tid, 0, xTask, pIn);
- }
- if( rc ){
- p->done = 1;
- p->pOut = xTask(pIn);
- }
- *ppThread = p;
- return SQLITE_OK;
-}
-
-/* Get the results of the thread */
-SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
- int rc;
-
- assert( ppOut!=0 );
- if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
- if( p->done ){
- *ppOut = p->pOut;
- rc = SQLITE_OK;
- }else{
- rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
- }
- sqlite3_free(p);
- return rc;
-}
-
-#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
-/******************************** End Unix Pthreads *************************/
-
-
-/********************************* Win32 Threads ****************************/
-#if SQLITE_OS_WIN_THREADS
-
-#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
-#include
-
-/* A running thread */
-struct SQLiteThread {
- void *tid; /* The thread handle */
- unsigned id; /* The thread identifier */
- void *(*xTask)(void*); /* The routine to run as a thread */
- void *pIn; /* Argument to xTask */
- void *pResult; /* Result of xTask */
-};
-
-/* Thread procedure Win32 compatibility shim */
-static unsigned __stdcall sqlite3ThreadProc(
- void *pArg /* IN: Pointer to the SQLiteThread structure */
-){
- SQLiteThread *p = (SQLiteThread *)pArg;
-
- assert( p!=0 );
-#if 0
- /*
- ** This assert appears to trigger spuriously on certain
- ** versions of Windows, possibly due to _beginthreadex()
- ** and/or CreateThread() not fully setting their thread
- ** ID parameter before starting the thread.
- */
- assert( p->id==GetCurrentThreadId() );
-#endif
- assert( p->xTask!=0 );
- p->pResult = p->xTask(p->pIn);
-
- _endthreadex(0);
- return 0; /* NOT REACHED */
-}
-
-/* Create a new thread */
-SQLITE_PRIVATE int sqlite3ThreadCreate(
- SQLiteThread **ppThread, /* OUT: Write the thread object here */
- void *(*xTask)(void*), /* Routine to run in a separate thread */
- void *pIn /* Argument passed into xTask() */
-){
- SQLiteThread *p;
-
- assert( ppThread!=0 );
- assert( xTask!=0 );
- *ppThread = 0;
- p = sqlite3Malloc(sizeof(*p));
- if( p==0 ) return SQLITE_NOMEM_BKPT;
- /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
- ** function that returns SQLITE_ERROR when passed the argument 200, that
- ** forces worker threads to run sequentially and deterministically
- ** (via the sqlite3FaultSim() term of the conditional) for testing
- ** purposes. */
- if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
- memset(p, 0, sizeof(*p));
- }else{
- p->xTask = xTask;
- p->pIn = pIn;
- p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
- if( p->tid==0 ){
- memset(p, 0, sizeof(*p));
- }
- }
- if( p->xTask==0 ){
- p->id = GetCurrentThreadId();
- p->pResult = xTask(pIn);
- }
- *ppThread = p;
- return SQLITE_OK;
-}
-
-SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
-
-/* Get the results of the thread */
-SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
- DWORD rc;
- BOOL bRc;
-
- assert( ppOut!=0 );
- if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
- if( p->xTask==0 ){
- /* assert( p->id==GetCurrentThreadId() ); */
- rc = WAIT_OBJECT_0;
- assert( p->tid==0 );
- }else{
- assert( p->id!=0 && p->id!=GetCurrentThreadId() );
- rc = sqlite3Win32Wait((HANDLE)p->tid);
- assert( rc!=WAIT_IO_COMPLETION );
- bRc = CloseHandle((HANDLE)p->tid);
- assert( bRc );
- }
- if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
- sqlite3_free(p);
- return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
-}
-
-#endif /* SQLITE_OS_WIN_THREADS */
-/******************************** End Win32 Threads *************************/
-
-
-/********************************* Single-Threaded **************************/
-#ifndef SQLITE_THREADS_IMPLEMENTED
-/*
-** This implementation does not actually create a new thread. It does the
-** work of the thread in the main thread, when either the thread is created
-** or when it is joined
-*/
-
-/* A running thread */
-struct SQLiteThread {
- void *(*xTask)(void*); /* The routine to run as a thread */
- void *pIn; /* Argument to xTask */
- void *pResult; /* Result of xTask */
-};
-
-/* Create a new thread */
-SQLITE_PRIVATE int sqlite3ThreadCreate(
- SQLiteThread **ppThread, /* OUT: Write the thread object here */
- void *(*xTask)(void*), /* Routine to run in a separate thread */
- void *pIn /* Argument passed into xTask() */
-){
- SQLiteThread *p;
-
- assert( ppThread!=0 );
- assert( xTask!=0 );
- *ppThread = 0;
- p = sqlite3Malloc(sizeof(*p));
- if( p==0 ) return SQLITE_NOMEM_BKPT;
- if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
- p->xTask = xTask;
- p->pIn = pIn;
- }else{
- p->xTask = 0;
- p->pResult = xTask(pIn);
- }
- *ppThread = p;
- return SQLITE_OK;
-}
-
-/* Get the results of the thread */
-SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
-
- assert( ppOut!=0 );
- if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
- if( p->xTask ){
- *ppOut = p->xTask(p->pIn);
- }else{
- *ppOut = p->pResult;
- }
- sqlite3_free(p);
-
-#if defined(SQLITE_TEST)
- {
- void *pTstAlloc = sqlite3Malloc(10);
- if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
- sqlite3_free(pTstAlloc);
- }
-#endif
-
- return SQLITE_OK;
-}
-
-#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
-/****************************** End Single-Threaded *************************/
-#endif /* SQLITE_MAX_WORKER_THREADS>0 */
-
-/************** End of threads.c *********************************************/
-/************** Begin file utf.c *********************************************/
-/*
-** 2004 April 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 routines used to translate between UTF-8,
-** UTF-16, UTF-16BE, and UTF-16LE.
-**
-** Notes on UTF-8:
-**
-** Byte-0 Byte-1 Byte-2 Byte-3 Value
-** 0xxxxxxx 00000000 00000000 0xxxxxxx
-** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
-** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
-** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
-**
-**
-** Notes on UTF-16: (with wwww+1==uuuuu)
-**
-** Word-0 Word-1 Value
-** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
-** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
-**
-**
-** BOM or Byte Order Mark:
-** 0xff 0xfe little-endian utf-16 follows
-** 0xfe 0xff big-endian utf-16 follows
-**
-*/
-/* #include "sqliteInt.h" */
-/* #include */
-/* #include "vdbeInt.h" */
-
-#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
-/*
-** The following constant value is used by the SQLITE_BIGENDIAN and
-** SQLITE_LITTLEENDIAN macros.
-*/
-SQLITE_PRIVATE const int sqlite3one = 1;
-#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
-
-/*
-** This lookup table is used to help decode the first byte of
-** a multi-byte UTF8 character.
-*/
-static const unsigned char sqlite3Utf8Trans1[] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
- 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
-};
-
-
-#define WRITE_UTF8(zOut, c) { \
- if( c<0x00080 ){ \
- *zOut++ = (u8)(c&0xFF); \
- } \
- else if( c<0x00800 ){ \
- *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
- *zOut++ = 0x80 + (u8)(c & 0x3F); \
- } \
- else if( c<0x10000 ){ \
- *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
- *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
- *zOut++ = 0x80 + (u8)(c & 0x3F); \
- }else{ \
- *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
- *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
- *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
- *zOut++ = 0x80 + (u8)(c & 0x3F); \
- } \
-}
-
-#define WRITE_UTF16LE(zOut, c) { \
- if( c<=0xFFFF ){ \
- *zOut++ = (u8)(c&0x00FF); \
- *zOut++ = (u8)((c>>8)&0x00FF); \
- }else{ \
- *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
- *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
- *zOut++ = (u8)(c&0x00FF); \
- *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
- } \
-}
-
-#define WRITE_UTF16BE(zOut, c) { \
- if( c<=0xFFFF ){ \
- *zOut++ = (u8)((c>>8)&0x00FF); \
- *zOut++ = (u8)(c&0x00FF); \
- }else{ \
- *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
- *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
- *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
- *zOut++ = (u8)(c&0x00FF); \
- } \
-}
-
-#define READ_UTF16LE(zIn, TERM, c){ \
- c = (*zIn++); \
- c += ((*zIn++)<<8); \
- if( c>=0xD800 && c<0xE000 && TERM ){ \
- int c2 = (*zIn++); \
- c2 += ((*zIn++)<<8); \
- c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
- } \
-}
-
-#define READ_UTF16BE(zIn, TERM, c){ \
- c = ((*zIn++)<<8); \
- c += (*zIn++); \
- if( c>=0xD800 && c<0xE000 && TERM ){ \
- int c2 = ((*zIn++)<<8); \
- c2 += (*zIn++); \
- c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
- } \
-}
-
-/*
-** Translate a single UTF-8 character. Return the unicode value.
-**
-** During translation, assume that the byte that zTerm points
-** is a 0x00.
-**
-** Write a pointer to the next unread byte back into *pzNext.
-**
-** Notes On Invalid UTF-8:
-**
-** * This routine never allows a 7-bit character (0x00 through 0x7f) to
-** be encoded as a multi-byte character. Any multi-byte character that
-** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
-**
-** * This routine never allows a UTF16 surrogate value to be encoded.
-** If a multi-byte character attempts to encode a value between
-** 0xd800 and 0xe000 then it is rendered as 0xfffd.
-**
-** * Bytes in the range of 0x80 through 0xbf which occur as the first
-** byte of a character are interpreted as single-byte characters
-** and rendered as themselves even though they are technically
-** invalid characters.
-**
-** * This routine accepts over-length UTF8 encodings
-** for unicode values 0x80 and greater. It does not change over-length
-** encodings to 0xfffd as some systems recommend.
-*/
-#define READ_UTF8(zIn, zTerm, c) \
- c = *(zIn++); \
- if( c>=0xc0 ){ \
- c = sqlite3Utf8Trans1[c-0xc0]; \
- while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
- c = (c<<6) + (0x3f & *(zIn++)); \
- } \
- if( c<0x80 \
- || (c&0xFFFFF800)==0xD800 \
- || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
- }
-SQLITE_PRIVATE u32 sqlite3Utf8Read(
- const unsigned char **pz /* Pointer to string from which to read char */
-){
- unsigned int c;
-
- /* Same as READ_UTF8() above but without the zTerm parameter.
- ** For this routine, we assume the UTF8 string is always zero-terminated.
- */
- c = *((*pz)++);
- if( c>=0xc0 ){
- c = sqlite3Utf8Trans1[c-0xc0];
- while( (*(*pz) & 0xc0)==0x80 ){
- c = (c<<6) + (0x3f & *((*pz)++));
- }
- if( c<0x80
- || (c&0xFFFFF800)==0xD800
- || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
- }
- return c;
-}
-
-
-
-
-/*
-** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
-** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
-*/
-/* #define TRANSLATE_TRACE 1 */
-
-#ifndef SQLITE_OMIT_UTF16
-/*
-** This routine transforms the internal text encoding used by pMem to
-** desiredEnc. It is an error if the string is already of the desired
-** encoding, or if *pMem does not contain a string value.
-*/
-SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
- sqlite3_int64 len; /* Maximum length of output string in bytes */
- unsigned char *zOut; /* Output buffer */
- unsigned char *zIn; /* Input iterator */
- unsigned char *zTerm; /* End of input */
- unsigned char *z; /* Output iterator */
- unsigned int c;
-
- assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
- assert( pMem->flags&MEM_Str );
- assert( pMem->enc!=desiredEnc );
- assert( pMem->enc!=0 );
- assert( pMem->n>=0 );
-
-#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
- {
- char zBuf[100];
- sqlite3VdbeMemPrettyPrint(pMem, zBuf);
- fprintf(stderr, "INPUT: %s\n", zBuf);
- }
-#endif
-
- /* If the translation is between UTF-16 little and big endian, then
- ** all that is required is to swap the byte order. This case is handled
- ** differently from the others.
- */
- if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
- u8 temp;
- int rc;
- rc = sqlite3VdbeMemMakeWriteable(pMem);
- if( rc!=SQLITE_OK ){
- assert( rc==SQLITE_NOMEM );
- return SQLITE_NOMEM_BKPT;
- }
- zIn = (u8*)pMem->z;
- zTerm = &zIn[pMem->n&~1];
- while( zInenc = desiredEnc;
- goto translate_out;
- }
-
- /* Set len to the maximum number of bytes required in the output buffer. */
- if( desiredEnc==SQLITE_UTF8 ){
- /* When converting from UTF-16, the maximum growth results from
- ** translating a 2-byte character to a 4-byte UTF-8 character.
- ** A single byte is required for the output string
- ** nul-terminator.
- */
- pMem->n &= ~1;
- len = 2 * (sqlite3_int64)pMem->n + 1;
- }else{
- /* When converting from UTF-8 to UTF-16 the maximum growth is caused
- ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
- ** character. Two bytes are required in the output buffer for the
- ** nul-terminator.
- */
- len = 2 * (sqlite3_int64)pMem->n + 2;
- }
-
- /* Set zIn to point at the start of the input buffer and zTerm to point 1
- ** byte past the end.
- **
- ** Variable zOut is set to point at the output buffer, space obtained
- ** from sqlite3_malloc().
- */
- zIn = (u8*)pMem->z;
- zTerm = &zIn[pMem->n];
- zOut = sqlite3DbMallocRaw(pMem->db, len);
- if( !zOut ){
- return SQLITE_NOMEM_BKPT;
- }
- z = zOut;
-
- if( pMem->enc==SQLITE_UTF8 ){
- if( desiredEnc==SQLITE_UTF16LE ){
- /* UTF-8 -> UTF-16 Little-endian */
- while( zIn UTF-16 Big-endian */
- while( zInn = (int)(z - zOut);
- *z++ = 0;
- }else{
- assert( desiredEnc==SQLITE_UTF8 );
- if( pMem->enc==SQLITE_UTF16LE ){
- /* UTF-16 Little-endian -> UTF-8 */
- while( zIn UTF-8 */
- while( zInn = (int)(z - zOut);
- }
- *z = 0;
- assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
-
- c = pMem->flags;
- sqlite3VdbeMemRelease(pMem);
- pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
- pMem->enc = desiredEnc;
- pMem->z = (char*)zOut;
- pMem->zMalloc = pMem->z;
- pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
-
-translate_out:
-#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
- {
- char zBuf[100];
- sqlite3VdbeMemPrettyPrint(pMem, zBuf);
- fprintf(stderr, "OUTPUT: %s\n", zBuf);
- }
-#endif
- return SQLITE_OK;
-}
-#endif /* SQLITE_OMIT_UTF16 */
-
-#ifndef SQLITE_OMIT_UTF16
-/*
-** This routine checks for a byte-order mark at the beginning of the
-** UTF-16 string stored in *pMem. If one is present, it is removed and
-** the encoding of the Mem adjusted. This routine does not do any
-** byte-swapping, it just sets Mem.enc appropriately.
-**
-** The allocation (static, dynamic etc.) and encoding of the Mem may be
-** changed by this function.
-*/
-SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
- int rc = SQLITE_OK;
- u8 bom = 0;
-
- assert( pMem->n>=0 );
- if( pMem->n>1 ){
- u8 b1 = *(u8 *)pMem->z;
- u8 b2 = *(((u8 *)pMem->z) + 1);
- if( b1==0xFE && b2==0xFF ){
- bom = SQLITE_UTF16BE;
- }
- if( b1==0xFF && b2==0xFE ){
- bom = SQLITE_UTF16LE;
- }
- }
-
- if( bom ){
- rc = sqlite3VdbeMemMakeWriteable(pMem);
- if( rc==SQLITE_OK ){
- pMem->n -= 2;
- memmove(pMem->z, &pMem->z[2], pMem->n);
- pMem->z[pMem->n] = '\0';
- pMem->z[pMem->n+1] = '\0';
- pMem->flags |= MEM_Term;
- pMem->enc = bom;
- }
- }
- return rc;
-}
-#endif /* SQLITE_OMIT_UTF16 */
-
-/*
-** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
-** return the number of unicode characters in pZ up to (but not including)
-** the first 0x00 byte. If nByte is not less than zero, return the
-** number of unicode characters in the first nByte of pZ (or up to
-** the first 0x00, whichever comes first).
-*/
-SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
- int r = 0;
- const u8 *z = (const u8*)zIn;
- const u8 *zTerm;
- if( nByte>=0 ){
- zTerm = &z[nByte];
- }else{
- zTerm = (const u8*)(-1);
- }
- assert( z<=zTerm );
- while( *z!=0 && zmallocFailed ){
- sqlite3VdbeMemRelease(&m);
- m.z = 0;
- }
- assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
- assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
- assert( m.z || db->mallocFailed );
- return m.z;
-}
-
-/*
-** zIn is a UTF-16 encoded unicode string at least nChar characters long.
-** Return the number of bytes in the first nChar unicode characters
-** in pZ. nChar must be non-negative.
-*/
-SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
- int c;
- unsigned char const *z = zIn;
- int n = 0;
-
- if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
- while( n0 && n<=4 );
- z[0] = 0;
- z = zBuf;
- c = sqlite3Utf8Read((const u8**)&z);
- t = i;
- if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
- if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
- assert( c==t );
- assert( (z-zBuf)==n );
- }
- for(i=0; i<0x00110000; i++){
- if( i>=0xD800 && i<0xE000 ) continue;
- z = zBuf;
- WRITE_UTF16LE(z, i);
- n = (int)(z-zBuf);
- assert( n>0 && n<=4 );
- z[0] = 0;
- z = zBuf;
- READ_UTF16LE(z, 1, c);
- assert( c==i );
- assert( (z-zBuf)==n );
- }
- for(i=0; i<0x00110000; i++){
- if( i>=0xD800 && i<0xE000 ) continue;
- z = zBuf;
- WRITE_UTF16BE(z, i);
- n = (int)(z-zBuf);
- assert( n>0 && n<=4 );
- z[0] = 0;
- z = zBuf;
- READ_UTF16BE(z, 1, c);
- assert( c==i );
- assert( (z-zBuf)==n );
- }
-}
-#endif /* SQLITE_TEST */
-#endif /* SQLITE_OMIT_UTF16 */
-
-/************** End of utf.c *************************************************/
-/************** Begin file util.c ********************************************/
-/*
-** 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.
-**
-*************************************************************************
-** Utility functions used throughout sqlite.
-**
-** This file contains functions for allocating memory, comparing
-** strings, and stuff like that.
-**
-*/
-/* #include "sqliteInt.h" */
-/* #include */
-#include
-
-/*
-** Routine needed to support the testcase() macro.
-*/
-#ifdef SQLITE_COVERAGE_TEST
-SQLITE_PRIVATE void sqlite3Coverage(int x){
- static unsigned dummy = 0;
- dummy += (unsigned)x;
-}
-#endif
-
-/*
-** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
-** or to bypass normal error detection during testing in order to let
-** execute proceed futher downstream.
-**
-** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
-** sqlite3FaultSim() function only returns non-zero during testing.
-**
-** During testing, if the test harness has set a fault-sim callback using
-** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
-** each call to sqlite3FaultSim() is relayed to that application-supplied
-** callback and the integer return value form the application-supplied
-** callback is returned by sqlite3FaultSim().
-**
-** The integer argument to sqlite3FaultSim() is a code to identify which
-** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
-** should have a unique code. To prevent legacy testing applications from
-** breaking, the codes should not be changed or reused.
-*/
-#ifndef SQLITE_UNTESTABLE
-SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
- int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
- return xCallback ? xCallback(iTest) : SQLITE_OK;
-}
-#endif
-
-#ifndef SQLITE_OMIT_FLOATING_POINT
-/*
-** Return true if the floating point value is Not a Number (NaN).
-*/
-SQLITE_PRIVATE int sqlite3IsNaN(double x){
- u64 y;
- memcpy(&y,&x,sizeof(y));
- return IsNaN(y);
-}
-#endif /* SQLITE_OMIT_FLOATING_POINT */
-
-/*
-** Compute a string length that is limited to what can be stored in
-** lower 30 bits of a 32-bit signed integer.
-**
-** The value returned will never be negative. Nor will it ever be greater
-** than the actual length of the string. For very long strings (greater
-** than 1GiB) the value returned might be less than the true string length.
-*/
-SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
- if( z==0 ) return 0;
- return 0x3fffffff & (int)strlen(z);
-}
-
-/*
-** Return the declared type of a column. Or return zDflt if the column
-** has no declared type.
-**
-** The column type is an extra string stored after the zero-terminator on
-** the column name if and only if the COLFLAG_HASTYPE flag is set.
-*/
-SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
- if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
- return pCol->zName + strlen(pCol->zName) + 1;
-}
-
-/*
-** Helper function for sqlite3Error() - called rarely. Broken out into
-** a separate routine to avoid unnecessary register saves on entry to
-** sqlite3Error().
-*/
-static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
- if( db->pErr ) sqlite3ValueSetNull(db->pErr);
- sqlite3SystemError(db, err_code);
-}
-
-/*
-** Set the current error code to err_code and clear any prior error message.
-** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
-** that would be appropriate.
-*/
-SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
- assert( db!=0 );
- db->errCode = err_code;
- if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
-}
-
-/*
-** Load the sqlite3.iSysErrno field if that is an appropriate thing
-** to do based on the SQLite error code in rc.
-*/
-SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
- if( rc==SQLITE_IOERR_NOMEM ) return;
- rc &= 0xff;
- if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
- db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
- }
-}
-
-/*
-** Set the most recent error code and error string for the sqlite
-** handle "db". The error code is set to "err_code".
-**
-** If it is not NULL, string zFormat specifies the format of the
-** error string in the style of the printf functions: The following
-** format characters are allowed:
-**
-** %s Insert a string
-** %z A string that should be freed after use
-** %d Insert an integer
-** %T Insert a token
-** %S Insert the first element of a SrcList
-**
-** zFormat and any string tokens that follow it are assumed to be
-** encoded in UTF-8.
-**
-** To clear the most recent error for sqlite handle "db", sqlite3Error
-** should be called with err_code set to SQLITE_OK and zFormat set
-** to NULL.
-*/
-SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
- assert( db!=0 );
- db->errCode = err_code;
- sqlite3SystemError(db, err_code);
- if( zFormat==0 ){
- sqlite3Error(db, err_code);
- }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
- char *z;
- va_list ap;
- va_start(ap, zFormat);
- z = sqlite3VMPrintf(db, zFormat, ap);
- va_end(ap);
- sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
- }
-}
-
-/*
-** Add an error message to pParse->zErrMsg and increment pParse->nErr.
-** The following formatting characters are allowed:
-**
-** %s Insert a string
-** %z A string that should be freed after use
-** %d Insert an integer
-** %T Insert a token
-** %S Insert the first element of a SrcList
-**
-** This function should be used to report any error that occurs while
-** compiling an SQL statement (i.e. within sqlite3_prepare()). The
-** last thing the sqlite3_prepare() function does is copy the error
-** stored by this function into the database handle using sqlite3Error().
-** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
-** during statement execution (sqlite3_step() etc.).
-*/
-SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
- char *zMsg;
- va_list ap;
- sqlite3 *db = pParse->db;
- va_start(ap, zFormat);
- zMsg = sqlite3VMPrintf(db, zFormat, ap);
- va_end(ap);
- if( db->suppressErr ){
- sqlite3DbFree(db, zMsg);
- }else{
- pParse->nErr++;
- sqlite3DbFree(db, pParse->zErrMsg);
- pParse->zErrMsg = zMsg;
- pParse->rc = SQLITE_ERROR;
- }
-}
-
-/*
-** If database connection db is currently parsing SQL, then transfer
-** error code errCode to that parser if the parser has not already
-** encountered some other kind of error.
-*/
-SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
- Parse *pParse;
- if( db==0 || (pParse = db->pParse)==0 ) return errCode;
- pParse->rc = errCode;
- pParse->nErr++;
- return errCode;
-}
-
-/*
-** Convert an SQL-style quoted string into a normal string by removing
-** the quote characters. The conversion is done in-place. If the
-** input does not begin with a quote character, then this routine
-** is a no-op.
-**
-** The input string must be zero-terminated. A new zero-terminator
-** is added to the dequoted string.
-**
-** The return value is -1 if no dequoting occurs or the length of the
-** dequoted string, exclusive of the zero terminator, if dequoting does
-** occur.
-**
-** 2002-02-14: This routine is extended to remove MS-Access style
-** brackets from around identifiers. For example: "[a-b-c]" becomes
-** "a-b-c".
-*/
-SQLITE_PRIVATE void sqlite3Dequote(char *z){
- char quote;
- int i, j;
- if( z==0 ) return;
- quote = z[0];
- if( !sqlite3Isquote(quote) ) return;
- if( quote=='[' ) quote = ']';
- for(i=1, j=0;; i++){
- assert( z[i] );
- if( z[i]==quote ){
- if( z[i+1]==quote ){
- z[j++] = quote;
- i++;
- }else{
- break;
- }
- }else{
- z[j++] = z[i];
- }
- }
- z[j] = 0;
-}
-SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
- assert( sqlite3Isquote(p->u.zToken[0]) );
- p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
- sqlite3Dequote(p->u.zToken);
-}
-
-/*
-** Generate a Token object from a string
-*/
-SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
- p->z = z;
- p->n = sqlite3Strlen30(z);
-}
-
-/* Convenient short-hand */
-#define UpperToLower sqlite3UpperToLower
-
-/*
-** Some systems have stricmp(). Others have strcasecmp(). Because
-** there is no consistency, we will define our own.
-**
-** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
-** sqlite3_strnicmp() APIs allow 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_stricmp(const char *zLeft, const char *zRight){
- if( zLeft==0 ){
- return zRight ? -1 : 0;
- }else if( zRight==0 ){
- return 1;
- }
- return sqlite3StrICmp(zLeft, zRight);
-}
-SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
- unsigned char *a, *b;
- int c, x;
- a = (unsigned char *)zLeft;
- b = (unsigned char *)zRight;
- for(;;){
- c = *a;
- x = *b;
- if( c==x ){
- if( c==0 ) break;
- }else{
- c = (int)UpperToLower[c] - (int)UpperToLower[x];
- if( c ) break;
- }
- a++;
- b++;
- }
- return c;
-}
-SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
- register unsigned char *a, *b;
- if( zLeft==0 ){
- return zRight ? -1 : 0;
- }else if( zRight==0 ){
- return 1;
- }
- a = (unsigned char *)zLeft;
- b = (unsigned char *)zRight;
- while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
- return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
-}
-
-/*
-** Compute 10 to the E-th power. Examples: E==1 results in 10.
-** E==2 results in 100. E==50 results in 1.0e50.
-**
-** This routine only works for values of E between 1 and 341.
-*/
-static LONGDOUBLE_TYPE sqlite3Pow10(int E){
-#if defined(_MSC_VER)
- static const LONGDOUBLE_TYPE x[] = {
- 1.0e+001L,
- 1.0e+002L,
- 1.0e+004L,
- 1.0e+008L,
- 1.0e+016L,
- 1.0e+032L,
- 1.0e+064L,
- 1.0e+128L,
- 1.0e+256L
- };
- LONGDOUBLE_TYPE r = 1.0;
- int i;
- assert( E>=0 && E<=307 );
- for(i=0; E!=0; i++, E >>=1){
- if( E & 1 ) r *= x[i];
- }
- return r;
-#else
- LONGDOUBLE_TYPE x = 10.0;
- LONGDOUBLE_TYPE r = 1.0;
- while(1){
- if( E & 1 ) r *= x;
- E >>= 1;
- if( E==0 ) break;
- x *= x;
- }
- return r;
-#endif
-}
-
-/*
-** The string z[] is an text representation of a real number.
-** Convert this string to a double and write it into *pResult.
-**
-** The string z[] is length bytes in length (bytes, not characters) and
-** uses the encoding enc. The string is not necessarily zero-terminated.
-**
-** Return TRUE if the result is a valid real number (or integer) and FALSE
-** if the string is empty or contains extraneous text. More specifically
-** return
-** 1 => The input string is a pure integer
-** 2 or more => The input has a decimal point or eNNN clause
-** 0 or less => The input string is not a valid number
-** -1 => Not a valid number, but has a valid prefix which
-** includes a decimal point and/or an eNNN clause
-**
-** Valid numbers are in one of these formats:
-**
-** [+-]digits[E[+-]digits]
-** [+-]digits.[digits][E[+-]digits]
-** [+-].digits[E[+-]digits]
-**
-** Leading and trailing whitespace is ignored for the purpose of determining
-** validity.
-**
-** If some prefix of the input string is a valid number, this routine
-** returns FALSE but it still converts the prefix and writes the result
-** into *pResult.
-*/
-SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
-#ifndef SQLITE_OMIT_FLOATING_POINT
- int incr;
- const char *zEnd = z + length;
- /* sign * significand * (10 ^ (esign * exponent)) */
- int sign = 1; /* sign of significand */
- i64 s = 0; /* significand */
- int d = 0; /* adjust exponent for shifting decimal point */
- int esign = 1; /* sign of exponent */
- int e = 0; /* exponent */
- int eValid = 1; /* True exponent is either not used or is well-formed */
- double result;
- int nDigit = 0; /* Number of digits processed */
- int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
-
- assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
- *pResult = 0.0; /* Default return value, in case of an error */
-
- if( enc==SQLITE_UTF8 ){
- incr = 1;
- }else{
- int i;
- incr = 2;
- assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
- testcase( enc==SQLITE_UTF16LE );
- testcase( enc==SQLITE_UTF16BE );
- for(i=3-enc; i=zEnd ) return 0;
-
- /* get sign of significand */
- if( *z=='-' ){
- sign = -1;
- z+=incr;
- }else if( *z=='+' ){
- z+=incr;
- }
-
- /* copy max significant digits to significand */
- while( z=((LARGEST_INT64-9)/10) ){
- /* skip non-significant significand digits
- ** (increase exponent by d to shift decimal left) */
- while( z=zEnd ) goto do_atof_calc;
-
- /* if decimal point is present */
- if( *z=='.' ){
- z+=incr;
- eType++;
- /* copy digits from after decimal to significand
- ** (decrease exponent by d to shift decimal right) */
- while( z=zEnd ) goto do_atof_calc;
-
- /* if exponent is present */
- if( *z=='e' || *z=='E' ){
- z+=incr;
- eValid = 0;
- eType++;
-
- /* This branch is needed to avoid a (harmless) buffer overread. The
- ** special comment alerts the mutation tester that the correct answer
- ** is obtained even if the branch is omitted */
- if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
-
- /* get sign of exponent */
- if( *z=='-' ){
- esign = -1;
- z+=incr;
- }else if( *z=='+' ){
- z+=incr;
- }
- /* copy digits to exponent */
- while( z0 ){ /*OPTIMIZATION-IF-TRUE*/
- if( esign>0 ){
- if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
- s *= 10;
- }else{
- if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
- s /= 10;
- }
- e--;
- }
-
- /* adjust the sign of significand */
- s = sign<0 ? -s : s;
-
- if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
- result = (double)s;
- }else{
- /* attempt to handle extremely small/large numbers better */
- if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
- if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
- LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
- if( esign<0 ){
- result = s / scale;
- result /= 1.0e+308;
- }else{
- result = s * scale;
- result *= 1.0e+308;
- }
- }else{ assert( e>=342 );
- if( esign<0 ){
- result = 0.0*s;
- }else{
-#ifdef INFINITY
- result = INFINITY*s;
-#else
- result = 1e308*1e308*s; /* Infinity */
-#endif
- }
- }
- }else{
- LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
- if( esign<0 ){
- result = s / scale;
- }else{
- result = s * scale;
- }
- }
- }
- }
-
- /* store the result */
- *pResult = result;
-
- /* return true if number and no extra non-whitespace chracters after */
- if( z==zEnd && nDigit>0 && eValid && eType>0 ){
- return eType;
- }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
- return -1;
- }else{
- return 0;
- }
-#else
- return !sqlite3Atoi64(z, pResult, length, enc);
-#endif /* SQLITE_OMIT_FLOATING_POINT */
-}
-
-/*
-** Compare the 19-character string zNum against the text representation
-** value 2^63: 9223372036854775808. Return negative, zero, or positive
-** if zNum is less than, equal to, or greater than the string.
-** Note that zNum must contain exactly 19 characters.
-**
-** Unlike memcmp() this routine is guaranteed to return the difference
-** in the values of the last digit if the only difference is in the
-** last digit. So, for example,
-**
-** compare2pow63("9223372036854775800", 1)
-**
-** will return -8.
-*/
-static int compare2pow63(const char *zNum, int incr){
- int c = 0;
- int i;
- /* 012345678901234567 */
- const char *pow63 = "922337203685477580";
- for(i=0; c==0 && i<18; i++){
- c = (zNum[i*incr]-pow63[i])*10;
- }
- if( c==0 ){
- c = zNum[18*incr] - '8';
- testcase( c==(-1) );
- testcase( c==0 );
- testcase( c==(+1) );
- }
- return c;
-}
-
-/*
-** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
-** routine does *not* accept hexadecimal notation.
-**
-** Returns:
-**
-** -1 Not even a prefix of the input text looks like an integer
-** 0 Successful transformation. Fits in a 64-bit signed integer.
-** 1 Excess non-space text after the integer value
-** 2 Integer too large for a 64-bit signed integer or is malformed
-** 3 Special case of 9223372036854775808
-**
-** length is the number of bytes in the string (bytes, not characters).
-** The string is not necessarily zero-terminated. The encoding is
-** given by enc.
-*/
-SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
- int incr;
- u64 u = 0;
- int neg = 0; /* assume positive */
- int i;
- int c = 0;
- int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
- int rc; /* Baseline return code */
- const char *zStart;
- const char *zEnd = zNum + length;
- assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
- if( enc==SQLITE_UTF8 ){
- incr = 1;
- }else{
- incr = 2;
- assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
- for(i=3-enc; i='0' && c<='9'; i+=incr){
- u = u*10 + c - '0';
- }
- testcase( i==18*incr );
- testcase( i==19*incr );
- testcase( i==20*incr );
- if( u>LARGEST_INT64 ){
- /* This test and assignment is needed only to suppress UB warnings
- ** from clang and -fsanitize=undefined. This test and assignment make
- ** the code a little larger and slower, and no harm comes from omitting
- ** them, but we must appaise the undefined-behavior pharisees. */
- *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
- }else if( neg ){
- *pNum = -(i64)u;
- }else{
- *pNum = (i64)u;
- }
- rc = 0;
- if( i==0 && zStart==zNum ){ /* No digits */
- rc = -1;
- }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
- rc = 1;
- }else if( &zNum[i]19*incr ? 1 : compare2pow63(zNum, incr);
- if( c<0 ){
- /* zNum is less than 9223372036854775808 so it fits */
- assert( u<=LARGEST_INT64 );
- return rc;
- }else{
- *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
- if( c>0 ){
- /* zNum is greater than 9223372036854775808 so it overflows */
- return 2;
- }else{
- /* zNum is exactly 9223372036854775808. Fits if negative. The
- ** special case 2 overflow if positive */
- assert( u-1==LARGEST_INT64 );
- return neg ? rc : 3;
- }
- }
- }
-}
-
-/*
-** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
-** into a 64-bit signed integer. This routine accepts hexadecimal literals,
-** whereas sqlite3Atoi64() does not.
-**
-** Returns:
-**
-** 0 Successful transformation. Fits in a 64-bit signed integer.
-** 1 Excess text after the integer value
-** 2 Integer too large for a 64-bit signed integer or is malformed
-** 3 Special case of 9223372036854775808
-*/
-SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
-#ifndef SQLITE_OMIT_HEX_INTEGER
- if( z[0]=='0'
- && (z[1]=='x' || z[1]=='X')
- ){
- u64 u = 0;
- int i, k;
- for(i=2; z[i]=='0'; i++){}
- for(k=i; sqlite3Isxdigit(z[k]); k++){
- u = u*16 + sqlite3HexToInt(z[k]);
- }
- memcpy(pOut, &u, 8);
- return (z[k]==0 && k-i<=16) ? 0 : 2;
- }else
-#endif /* SQLITE_OMIT_HEX_INTEGER */
- {
- return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
- }
-}
-
-/*
-** If zNum represents an integer that will fit in 32-bits, then set
-** *pValue to that integer and return true. Otherwise return false.
-**
-** This routine accepts both decimal and hexadecimal notation for integers.
-**
-** Any non-numeric characters that following zNum are ignored.
-** This is different from sqlite3Atoi64() which requires the
-** input number to be zero-terminated.
-*/
-SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
- sqlite_int64 v = 0;
- int i, c;
- int neg = 0;
- if( zNum[0]=='-' ){
- neg = 1;
- zNum++;
- }else if( zNum[0]=='+' ){
- zNum++;
- }
-#ifndef SQLITE_OMIT_HEX_INTEGER
- else if( zNum[0]=='0'
- && (zNum[1]=='x' || zNum[1]=='X')
- && sqlite3Isxdigit(zNum[2])
- ){
- u32 u = 0;
- zNum += 2;
- while( zNum[0]=='0' ) zNum++;
- for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
- u = u*16 + sqlite3HexToInt(zNum[i]);
- }
- if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
- memcpy(pValue, &u, 4);
- return 1;
- }else{
- return 0;
- }
- }
-#endif
- if( !sqlite3Isdigit(zNum[0]) ) return 0;
- while( zNum[0]=='0' ) zNum++;
- for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
- v = v*10 + c;
- }
-
- /* The longest decimal representation of a 32 bit integer is 10 digits:
- **
- ** 1234567890
- ** 2^31 -> 2147483648
- */
- testcase( i==10 );
- if( i>10 ){
- return 0;
- }
- testcase( v-neg==2147483647 );
- if( v-neg>2147483647 ){
- return 0;
- }
- if( neg ){
- v = -v;
- }
- *pValue = (int)v;
- return 1;
-}
-
-/*
-** Return a 32-bit integer value extracted from a string. If the
-** string is not an integer, just return 0.
-*/
-SQLITE_PRIVATE int sqlite3Atoi(const char *z){
- int x = 0;
- if( z ) sqlite3GetInt32(z, &x);
- return x;
-}
-
-/*
-** The variable-length integer encoding is as follows:
-**
-** KEY:
-** A = 0xxxxxxx 7 bits of data and one flag bit
-** B = 1xxxxxxx 7 bits of data and one flag bit
-** C = xxxxxxxx 8 bits of data
-**
-** 7 bits - A
-** 14 bits - BA
-** 21 bits - BBA
-** 28 bits - BBBA
-** 35 bits - BBBBA
-** 42 bits - BBBBBA
-** 49 bits - BBBBBBA
-** 56 bits - BBBBBBBA
-** 64 bits - BBBBBBBBC
-*/
-
-/*
-** Write a 64-bit variable-length integer to memory starting at p[0].
-** The length of data write will be between 1 and 9 bytes. The number
-** of bytes written is returned.
-**
-** A variable-length integer consists of the lower 7 bits of each byte
-** for all bytes that have the 8th bit set and one byte with the 8th
-** bit clear. Except, if we get to the 9th byte, it stores the full
-** 8 bits and is the last byte.
-*/
-static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
- int i, j, n;
- u8 buf[10];
- if( v & (((u64)0xff000000)<<32) ){
- p[8] = (u8)v;
- v >>= 8;
- for(i=7; i>=0; i--){
- p[i] = (u8)((v & 0x7f) | 0x80);
- v >>= 7;
- }
- return 9;
- }
- n = 0;
- do{
- buf[n++] = (u8)((v & 0x7f) | 0x80);
- v >>= 7;
- }while( v!=0 );
- buf[0] &= 0x7f;
- assert( n<=9 );
- for(i=0, j=n-1; j>=0; j--, i++){
- p[i] = buf[j];
- }
- return n;
-}
-SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
- if( v<=0x7f ){
- p[0] = v&0x7f;
- return 1;
- }
- if( v<=0x3fff ){
- p[0] = ((v>>7)&0x7f)|0x80;
- p[1] = v&0x7f;
- return 2;
- }
- return putVarint64(p,v);
-}
-
-/*
-** Bitmasks used by sqlite3GetVarint(). These precomputed constants
-** are defined here rather than simply putting the constant expressions
-** inline in order to work around bugs in the RVT compiler.
-**
-** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
-**
-** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
-*/
-#define SLOT_2_0 0x001fc07f
-#define SLOT_4_2_0 0xf01fc07f
-
-
-/*
-** Read a 64-bit variable-length integer from memory starting at p[0].
-** Return the number of bytes read. The value is stored in *v.
-*/
-SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
- u32 a,b,s;
-
- if( ((signed char*)p)[0]>=0 ){
- *v = *p;
- return 1;
- }
- if( ((signed char*)p)[1]>=0 ){
- *v = ((u32)(p[0]&0x7f)<<7) | p[1];
- return 2;
- }
-
- /* Verify that constants are precomputed correctly */
- assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
- assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
-
- a = ((u32)p[0])<<14;
- b = p[1];
- p += 2;
- a |= *p;
- /* a: p0<<14 | p2 (unmasked) */
- if (!(a&0x80))
- {
- a &= SLOT_2_0;
- b &= 0x7f;
- b = b<<7;
- a |= b;
- *v = a;
- return 3;
- }
-
- /* CSE1 from below */
- a &= SLOT_2_0;
- p++;
- b = b<<14;
- b |= *p;
- /* b: p1<<14 | p3 (unmasked) */
- if (!(b&0x80))
- {
- b &= SLOT_2_0;
- /* moved CSE1 up */
- /* a &= (0x7f<<14)|(0x7f); */
- a = a<<7;
- a |= b;
- *v = a;
- return 4;
- }
-
- /* a: p0<<14 | p2 (masked) */
- /* b: p1<<14 | p3 (unmasked) */
- /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
- /* moved CSE1 up */
- /* a &= (0x7f<<14)|(0x7f); */
- b &= SLOT_2_0;
- s = a;
- /* s: p0<<14 | p2 (masked) */
-
- p++;
- a = a<<14;
- a |= *p;
- /* a: p0<<28 | p2<<14 | p4 (unmasked) */
- if (!(a&0x80))
- {
- /* we can skip these cause they were (effectively) done above
- ** while calculating s */
- /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
- /* b &= (0x7f<<14)|(0x7f); */
- b = b<<7;
- a |= b;
- s = s>>18;
- *v = ((u64)s)<<32 | a;
- return 5;
- }
-
- /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
- s = s<<7;
- s |= b;
- /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
-
- p++;
- b = b<<14;
- b |= *p;
- /* b: p1<<28 | p3<<14 | p5 (unmasked) */
- if (!(b&0x80))
- {
- /* we can skip this cause it was (effectively) done above in calc'ing s */
- /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
- a &= SLOT_2_0;
- a = a<<7;
- a |= b;
- s = s>>18;
- *v = ((u64)s)<<32 | a;
- return 6;
- }
-
- p++;
- a = a<<14;
- a |= *p;
- /* a: p2<<28 | p4<<14 | p6 (unmasked) */
- if (!(a&0x80))
- {
- a &= SLOT_4_2_0;
- b &= SLOT_2_0;
- b = b<<7;
- a |= b;
- s = s>>11;
- *v = ((u64)s)<<32 | a;
- return 7;
- }
-
- /* CSE2 from below */
- a &= SLOT_2_0;
- p++;
- b = b<<14;
- b |= *p;
- /* b: p3<<28 | p5<<14 | p7 (unmasked) */
- if (!(b&0x80))
- {
- b &= SLOT_4_2_0;
- /* moved CSE2 up */
- /* a &= (0x7f<<14)|(0x7f); */
- a = a<<7;
- a |= b;
- s = s>>4;
- *v = ((u64)s)<<32 | a;
- return 8;
- }
-
- p++;
- a = a<<15;
- a |= *p;
- /* a: p4<<29 | p6<<15 | p8 (unmasked) */
-
- /* moved CSE2 up */
- /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
- b &= SLOT_2_0;
- b = b<<8;
- a |= b;
-
- s = s<<4;
- b = p[-4];
- b &= 0x7f;
- b = b>>3;
- s |= b;
-
- *v = ((u64)s)<<32 | a;
-
- return 9;
-}
-
-/*
-** Read a 32-bit variable-length integer from memory starting at p[0].
-** Return the number of bytes read. The value is stored in *v.
-**
-** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
-** integer, then set *v to 0xffffffff.
-**
-** A MACRO version, getVarint32, is provided which inlines the
-** single-byte case. All code should use the MACRO version as
-** this function assumes the single-byte case has already been handled.
-*/
-SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
- u32 a,b;
-
- /* The 1-byte case. Overwhelmingly the most common. Handled inline
- ** by the getVarin32() macro */
- a = *p;
- /* a: p0 (unmasked) */
-#ifndef getVarint32
- if (!(a&0x80))
- {
- /* Values between 0 and 127 */
- *v = a;
- return 1;
- }
-#endif
-
- /* The 2-byte case */
- p++;
- b = *p;
- /* b: p1 (unmasked) */
- if (!(b&0x80))
- {
- /* Values between 128 and 16383 */
- a &= 0x7f;
- a = a<<7;
- *v = a | b;
- return 2;
- }
-
- /* The 3-byte case */
- p++;
- a = a<<14;
- a |= *p;
- /* a: p0<<14 | p2 (unmasked) */
- if (!(a&0x80))
- {
- /* Values between 16384 and 2097151 */
- a &= (0x7f<<14)|(0x7f);
- b &= 0x7f;
- b = b<<7;
- *v = a | b;
- return 3;
- }
-
- /* A 32-bit varint is used to store size information in btrees.
- ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
- ** A 3-byte varint is sufficient, for example, to record the size
- ** of a 1048569-byte BLOB or string.
- **
- ** We only unroll the first 1-, 2-, and 3- byte cases. The very
- ** rare larger cases can be handled by the slower 64-bit varint
- ** routine.
- */
-#if 1
- {
- u64 v64;
- u8 n;
-
- p -= 2;
- n = sqlite3GetVarint(p, &v64);
- assert( n>3 && n<=9 );
- if( (v64 & SQLITE_MAX_U32)!=v64 ){
- *v = 0xffffffff;
- }else{
- *v = (u32)v64;
- }
- return n;
- }
-
-#else
- /* For following code (kept for historical record only) shows an
- ** unrolling for the 3- and 4-byte varint cases. This code is
- ** slightly faster, but it is also larger and much harder to test.
- */
- p++;
- b = b<<14;
- b |= *p;
- /* b: p1<<14 | p3 (unmasked) */
- if (!(b&0x80))
- {
- /* Values between 2097152 and 268435455 */
- b &= (0x7f<<14)|(0x7f);
- a &= (0x7f<<14)|(0x7f);
- a = a<<7;
- *v = a | b;
- return 4;
- }
-
- p++;
- a = a<<14;
- a |= *p;
- /* a: p0<<28 | p2<<14 | p4 (unmasked) */
- if (!(a&0x80))
- {
- /* Values between 268435456 and 34359738367 */
- a &= SLOT_4_2_0;
- b &= SLOT_4_2_0;
- b = b<<7;
- *v = a | b;
- return 5;
- }
-
- /* We can only reach this point when reading a corrupt database
- ** file. In that case we are not in any hurry. Use the (relatively
- ** slow) general-purpose sqlite3GetVarint() routine to extract the
- ** value. */
- {
- u64 v64;
- u8 n;
-
- p -= 4;
- n = sqlite3GetVarint(p, &v64);
- assert( n>5 && n<=9 );
- *v = (u32)v64;
- return n;
- }
-#endif
-}
-
-/*
-** Return the number of bytes that will be needed to store the given
-** 64-bit integer.
-*/
-SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
- int i;
- for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
- return i;
-}
-
-
-/*
-** Read or write a four-byte big-endian integer value.
-*/
-SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
-#if SQLITE_BYTEORDER==4321
- u32 x;
- memcpy(&x,p,4);
- return x;
-#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
- u32 x;
- memcpy(&x,p,4);
- return __builtin_bswap32(x);
-#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
- u32 x;
- memcpy(&x,p,4);
- return _byteswap_ulong(x);
-#else
- testcase( p[0]&0x80 );
- return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
-#endif
-}
-SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
-#if SQLITE_BYTEORDER==4321
- memcpy(p,&v,4);
-#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
- u32 x = __builtin_bswap32(v);
- memcpy(p,&x,4);
-#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
- u32 x = _byteswap_ulong(v);
- memcpy(p,&x,4);
-#else
- p[0] = (u8)(v>>24);
- p[1] = (u8)(v>>16);
- p[2] = (u8)(v>>8);
- p[3] = (u8)v;
-#endif
-}
-
-
-
-/*
-** Translate a single byte of Hex into an integer.
-** This routine only works if h really is a valid hexadecimal
-** character: 0..9a..fA..F
-*/
-SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
- assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
-#ifdef SQLITE_ASCII
- h += 9*(1&(h>>6));
-#endif
-#ifdef SQLITE_EBCDIC
- h += 9*(1&~(h>>4));
-#endif
- return (u8)(h & 0xf);
-}
-
-#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
-/*
-** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
-** value. Return a pointer to its binary value. Space to hold the
-** binary value has been obtained from malloc and must be freed by
-** the calling routine.
-*/
-SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
- char *zBlob;
- int i;
-
- zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
- n--;
- if( zBlob ){
- for(i=0; imagic;
- if( magic!=SQLITE_MAGIC_OPEN ){
- if( sqlite3SafetyCheckSickOrOk(db) ){
- testcase( sqlite3GlobalConfig.xLog!=0 );
- logBadConnection("unopened");
- }
- return 0;
- }else{
- return 1;
- }
-}
-SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
- u32 magic;
- magic = db->magic;
- if( magic!=SQLITE_MAGIC_SICK &&
- magic!=SQLITE_MAGIC_OPEN &&
- magic!=SQLITE_MAGIC_BUSY ){
- testcase( sqlite3GlobalConfig.xLog!=0 );
- logBadConnection("invalid");
- return 0;
- }else{
- return 1;
- }
-}
-
-/*
-** Attempt to add, substract, or multiply the 64-bit signed value iB against
-** the other 64-bit signed integer at *pA and store the result in *pA.
-** Return 0 on success. Or if the operation would have resulted in an
-** overflow, leave *pA unchanged and return 1.
-*/
-SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
-#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
- return __builtin_add_overflow(*pA, iB, pA);
-#else
- i64 iA = *pA;
- testcase( iA==0 ); testcase( iA==1 );
- testcase( iB==-1 ); testcase( iB==0 );
- if( iB>=0 ){
- testcase( iA>0 && LARGEST_INT64 - iA == iB );
- testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
- if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
- }else{
- testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
- testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
- if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
- }
- *pA += iB;
- return 0;
-#endif
-}
-SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
-#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
- return __builtin_sub_overflow(*pA, iB, pA);
-#else
- testcase( iB==SMALLEST_INT64+1 );
- if( iB==SMALLEST_INT64 ){
- testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
- if( (*pA)>=0 ) return 1;
- *pA -= iB;
- return 0;
- }else{
- return sqlite3AddInt64(pA, -iB);
- }
-#endif
-}
-SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
-#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
- return __builtin_mul_overflow(*pA, iB, pA);
-#else
- i64 iA = *pA;
- if( iB>0 ){
- if( iA>LARGEST_INT64/iB ) return 1;
- if( iA0 ){
- if( iBLARGEST_INT64/-iB ) return 1;
- }
- }
- *pA = iA*iB;
- return 0;
-#endif
-}
-
-/*
-** Compute the absolute value of a 32-bit signed integer, of possible. Or
-** if the integer has a value of -2147483648, return +2147483647
-*/
-SQLITE_PRIVATE int sqlite3AbsInt32(int x){
- if( x>=0 ) return x;
- if( x==(int)0x80000000 ) return 0x7fffffff;
- return -x;
-}
-
-#ifdef SQLITE_ENABLE_8_3_NAMES
-/*
-** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
-** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
-** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
-** three characters, then shorten the suffix on z[] to be the last three
-** characters of the original suffix.
-**
-** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
-** do the suffix shortening regardless of URI parameter.
-**
-** Examples:
-**
-** test.db-journal => test.nal
-** test.db-wal => test.wal
-** test.db-shm => test.shm
-** test.db-mj7f3319fa => test.9fa
-*/
-SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
-#if SQLITE_ENABLE_8_3_NAMES<2
- if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
-#endif
- {
- int i, sz;
- sz = sqlite3Strlen30(z);
- for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
- if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
- }
-}
-#endif
-
-/*
-** Find (an approximate) sum of two LogEst values. This computation is
-** not a simple "+" operator because LogEst is stored as a logarithmic
-** value.
-**
-*/
-SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
- static const unsigned char x[] = {
- 10, 10, /* 0,1 */
- 9, 9, /* 2,3 */
- 8, 8, /* 4,5 */
- 7, 7, 7, /* 6,7,8 */
- 6, 6, 6, /* 9,10,11 */
- 5, 5, 5, /* 12-14 */
- 4, 4, 4, 4, /* 15-18 */
- 3, 3, 3, 3, 3, 3, /* 19-24 */
- 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
- };
- if( a>=b ){
- if( a>b+49 ) return a;
- if( a>b+31 ) return a+1;
- return a+x[a-b];
- }else{
- if( b>a+49 ) return b;
- if( b>a+31 ) return b+1;
- return b+x[b-a];
- }
-}
-
-/*
-** Convert an integer into a LogEst. In other words, compute an
-** approximation for 10*log2(x).
-*/
-SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
- static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
- LogEst y = 40;
- if( x<8 ){
- if( x<2 ) return 0;
- while( x<8 ){ y -= 10; x <<= 1; }
- }else{
-#if GCC_VERSION>=5004000
- int i = 60 - __builtin_clzll(x);
- y += i*10;
- x >>= i;
-#else
- while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
- while( x>15 ){ y += 10; x >>= 1; }
-#endif
- }
- return a[x&7] + y - 10;
-}
-
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-/*
-** Convert a double into a LogEst
-** In other words, compute an approximation for 10*log2(x).
-*/
-SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
- u64 a;
- LogEst e;
- assert( sizeof(x)==8 && sizeof(a)==8 );
- if( x<=1 ) return 0;
- if( x<=2000000000 ) return sqlite3LogEst((u64)x);
- memcpy(&a, &x, 8);
- e = (a>>52) - 1022;
- return e*10;
-}
-#endif /* SQLITE_OMIT_VIRTUALTABLE */
-
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
- defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
- defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
-/*
-** Convert a LogEst into an integer.
-**
-** Note that this routine is only used when one or more of various
-** non-standard compile-time options is enabled.
-*/
-SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
- u64 n;
- n = x%10;
- x /= 10;
- if( n>=5 ) n -= 2;
- else if( n>=1 ) n -= 1;
-#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
- defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
- if( x>60 ) return (u64)LARGEST_INT64;
-#else
- /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
- ** possible to this routine is 310, resulting in a maximum x of 31 */
- assert( x<=60 );
-#endif
- return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
-}
-#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
-
-/*
-** Add a new name/number pair to a VList. This might require that the
-** VList object be reallocated, so return the new VList. If an OOM
-** error occurs, the original VList returned and the
-** db->mallocFailed flag is set.
-**
-** A VList is really just an array of integers. To destroy a VList,
-** simply pass it to sqlite3DbFree().
-**
-** The first integer is the number of integers allocated for the whole
-** VList. The second integer is the number of integers actually used.
-** Each name/number pair is encoded by subsequent groups of 3 or more
-** integers.
-**
-** Each name/number pair starts with two integers which are the numeric
-** value for the pair and the size of the name/number pair, respectively.
-** The text name overlays one or more following integers. The text name
-** is always zero-terminated.
-**
-** Conceptually:
-**
-** struct VList {
-** int nAlloc; // Number of allocated slots
-** int nUsed; // Number of used slots
-** struct VListEntry {
-** int iValue; // Value for this entry
-** int nSlot; // Slots used by this entry
-** // ... variable name goes here
-** } a[0];
-** }
-**
-** During code generation, pointers to the variable names within the
-** VList are taken. When that happens, nAlloc is set to zero as an
-** indication that the VList may never again be enlarged, since the
-** accompanying realloc() would invalidate the pointers.
-*/
-SQLITE_PRIVATE VList *sqlite3VListAdd(
- sqlite3 *db, /* The database connection used for malloc() */
- VList *pIn, /* The input VList. Might be NULL */
- const char *zName, /* Name of symbol to add */
- int nName, /* Bytes of text in zName */
- int iVal /* Value to associate with zName */
-){
- int nInt; /* number of sizeof(int) objects needed for zName */
- char *z; /* Pointer to where zName will be stored */
- int i; /* Index in pIn[] where zName is stored */
-
- nInt = nName/4 + 3;
- assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
- if( pIn==0 || pIn[1]+nInt > pIn[0] ){
- /* Enlarge the allocation */
- sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
- VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
- if( pOut==0 ) return pIn;
- if( pIn==0 ) pOut[1] = 2;
- pIn = pOut;
- pIn[0] = nAlloc;
- }
- i = pIn[1];
- pIn[i] = iVal;
- pIn[i+1] = nInt;
- z = (char*)&pIn[i+2];
- pIn[1] = i+nInt;
- assert( pIn[1]<=pIn[0] );
- memcpy(z, zName, nName);
- z[nName] = 0;
- return pIn;
-}
-
-/*
-** Return a pointer to the name of a variable in the given VList that
-** has the value iVal. Or return a NULL if there is no such variable in
-** the list
-*/
-SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
- int i, mx;
- if( pIn==0 ) return 0;
- mx = pIn[1];
- i = 2;
- do{
- if( pIn[i]==iVal ) return (char*)&pIn[i+2];
- i += pIn[i+1];
- }while( i */
-
-/* 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.
-*/
-SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
- assert( pNew!=0 );
- pNew->first = 0;
- pNew->count = 0;
- pNew->htsize = 0;
- pNew->ht = 0;
-}
-
-/* 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.
-*/
-SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
- HashElem *elem; /* For looping over all elements of the table */
-
- assert( pH!=0 );
- elem = pH->first;
- pH->first = 0;
- sqlite3_free(pH->ht);
- pH->ht = 0;
- pH->htsize = 0;
- while( elem ){
- HashElem *next_elem = elem->next;
- sqlite3_free(elem);
- elem = next_elem;
- }
- pH->count = 0;
-}
-
-/*
-** The hashing function.
-*/
-static unsigned int strHash(const char *z){
- unsigned int h = 0;
- unsigned char c;
- while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
- /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
- ** 0x9e3779b1 is 2654435761 which is the closest prime number to
- ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
- h += sqlite3UpperToLower[c];
- h *= 0x9e3779b1;
- }
- return 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 */
- struct _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 ){
- pHead = pEntry->count ? pEntry->chain : 0;
- pEntry->count++;
- pEntry->chain = pNew;
- }else{
- pHead = 0;
- }
- if( pHead ){
- pNew->next = pHead;
- pNew->prev = pHead->prev;
- if( pHead->prev ){ pHead->prev->next = pNew; }
- else { pH->first = pNew; }
- pHead->prev = pNew;
- }else{
- pNew->next = pH->first;
- if( pH->first ){ pH->first->prev = pNew; }
- pNew->prev = 0;
- 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 int rehash(Hash *pH, unsigned int new_size){
- struct _ht *new_ht; /* The new hash table */
- HashElem *elem, *next_elem; /* For looping over existing elements */
-
-#if SQLITE_MALLOC_SOFT_LIMIT>0
- 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 0;
-#endif
-
- /* The inability to allocates space for a larger hash table is
- ** a performance hit but it is not a fatal error. So mark the
- ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
- ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
- ** only zeroes the requested number of bytes whereas this module will
- ** use the actual amount of space allocated for the hash table (which
- ** may be larger than the requested amount).
- */
- sqlite3BeginBenignMalloc();
- new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
- sqlite3EndBenignMalloc();
-
- if( new_ht==0 ) return 0;
- sqlite3_free(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));
- for(elem=pH->first, pH->first=0; elem; elem = next_elem){
- unsigned int h = strHash(elem->pKey) % new_size;
- next_elem = elem->next;
- insertElement(pH, &new_ht[h], elem);
- }
- return 1;
-}
-
-/* This function (for internal use only) locates an element in an
-** hash table that matches the given key. If no element is found,
-** a pointer to a static null element with HashElem.data==0 is returned.
-** If pH is not NULL, then the hash for this key is written to *pH.
-*/
-static HashElem *findElementWithHash(
- const Hash *pH, /* The pH to be searched */
- const char *pKey, /* The key we are searching for */
- unsigned int *pHash /* Write the hash value here */
-){
- HashElem *elem; /* Used to loop thru the element list */
- unsigned int count; /* Number of elements left to test */
- unsigned int h; /* The computed hash */
- static HashElem nullElement = { 0, 0, 0, 0 };
-
- if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
- struct _ht *pEntry;
- h = strHash(pKey) % pH->htsize;
- pEntry = &pH->ht[h];
- elem = pEntry->chain;
- count = pEntry->count;
- }else{
- h = 0;
- elem = pH->first;
- count = pH->count;
- }
- if( pHash ) *pHash = h;
- while( count-- ){
- assert( elem!=0 );
- if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
- return elem;
- }
- elem = elem->next;
- }
- return &nullElement;
-}
-
-/* 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" */
- HashElem* elem, /* The element to be removed from the pH */
- unsigned int h /* Hash value for the element */
-){
- struct _ht *pEntry;
- if( elem->prev ){
- elem->prev->next = elem->next;
- }else{
- pH->first = elem->next;
- }
- if( elem->next ){
- elem->next->prev = elem->prev;
- }
- if( pH->ht ){
- pEntry = &pH->ht[h];
- if( pEntry->chain==elem ){
- pEntry->chain = elem->next;
- }
- assert( pEntry->count>0 );
- pEntry->count--;
- }
- sqlite3_free( elem );
- pH->count--;
- if( pH->count==0 ){
- assert( pH->first==0 );
- assert( pH->count==0 );
- sqlite3HashClear(pH);
- }
-}
-
-/* Attempt to locate an element of the hash table pH with a key
-** that matches pKey. Return the data for this element if it is
-** found, or NULL if there is no match.
-*/
-SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
- assert( pH!=0 );
- assert( pKey!=0 );
- return findElementWithHash(pH, pKey, 0)->data;
-}
-
-/* Insert an element into the hash table pH. The key is pKey
-** 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.
-*/
-SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
- unsigned int 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 */
-
- assert( pH!=0 );
- assert( pKey!=0 );
- elem = findElementWithHash(pH,pKey,&h);
- if( elem->data ){
- void *old_data = elem->data;
- if( data==0 ){
- removeElementGivenHash(pH,elem,h);
- }else{
- elem->data = data;
- elem->pKey = pKey;
- }
- return old_data;
- }
- if( data==0 ) return 0;
- new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
- if( new_elem==0 ) return data;
- new_elem->pKey = pKey;
- new_elem->data = data;
- pH->count++;
- if( pH->count>=10 && pH->count > 2*pH->htsize ){
- if( rehash(pH, pH->count*2) ){
- assert( pH->htsize>0 );
- h = strHash(pKey) % pH->htsize;
- }
- }
- insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
- return 0;
-}
-
-/************** End of hash.c ************************************************/
-/************** Begin file opcodes.c *****************************************/
-/* Automatically generated. Do not edit */
-/* See the tool/mkopcodec.tcl script for details. */
-#if !defined(SQLITE_OMIT_EXPLAIN) \
- || defined(VDBE_PROFILE) \
- || defined(SQLITE_DEBUG)
-#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
-# define OpHelp(X) "\0" X
-#else
-# define OpHelp(X)
-#endif
-SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
- static const char *const azName[] = {
- /* 0 */ "Savepoint" OpHelp(""),
- /* 1 */ "AutoCommit" OpHelp(""),
- /* 2 */ "Transaction" OpHelp(""),
- /* 3 */ "SorterNext" OpHelp(""),
- /* 4 */ "Prev" OpHelp(""),
- /* 5 */ "Next" OpHelp(""),
- /* 6 */ "Checkpoint" OpHelp(""),
- /* 7 */ "JournalMode" OpHelp(""),
- /* 8 */ "Vacuum" OpHelp(""),
- /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
- /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
- /* 11 */ "Goto" OpHelp(""),
- /* 12 */ "Gosub" OpHelp(""),
- /* 13 */ "InitCoroutine" OpHelp(""),
- /* 14 */ "Yield" OpHelp(""),
- /* 15 */ "MustBeInt" OpHelp(""),
- /* 16 */ "Jump" OpHelp(""),
- /* 17 */ "Once" OpHelp(""),
- /* 18 */ "If" OpHelp(""),
- /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
- /* 20 */ "IfNot" OpHelp(""),
- /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
- /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
- /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
- /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
- /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
- /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
- /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"),
- /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"),
- /* 29 */ "Found" OpHelp("key=r[P3@P4]"),
- /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"),
- /* 31 */ "NotExists" OpHelp("intkey=r[P3]"),
- /* 32 */ "Last" OpHelp(""),
- /* 33 */ "IfSmaller" OpHelp(""),
- /* 34 */ "SorterSort" OpHelp(""),
- /* 35 */ "Sort" OpHelp(""),
- /* 36 */ "Rewind" OpHelp(""),
- /* 37 */ "IdxLE" OpHelp("key=r[P3@P4]"),
- /* 38 */ "IdxGT" OpHelp("key=r[P3@P4]"),
- /* 39 */ "IdxLT" OpHelp("key=r[P3@P4]"),
- /* 40 */ "IdxGE" OpHelp("key=r[P3@P4]"),
- /* 41 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
- /* 42 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
- /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
- /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
- /* 45 */ "Program" OpHelp(""),
- /* 46 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
- /* 47 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
- /* 48 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
- /* 49 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
- /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
- /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
- /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
- /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
- /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
- /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
- /* 56 */ "Lt" OpHelp("IF r[P3]=r[P1]"),
- /* 58 */ "ElseNotEq" OpHelp(""),
- /* 59 */ "IncrVacuum" OpHelp(""),
- /* 60 */ "VNext" OpHelp(""),
- /* 61 */ "Init" OpHelp("Start at P2"),
- /* 62 */ "PureFunc0" OpHelp(""),
- /* 63 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
- /* 64 */ "PureFunc" OpHelp(""),
- /* 65 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
- /* 66 */ "Return" OpHelp(""),
- /* 67 */ "EndCoroutine" OpHelp(""),
- /* 68 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
- /* 69 */ "Halt" OpHelp(""),
- /* 70 */ "Integer" OpHelp("r[P2]=P1"),
- /* 71 */ "Int64" OpHelp("r[P2]=P4"),
- /* 72 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
- /* 73 */ "Null" OpHelp("r[P2..P3]=NULL"),
- /* 74 */ "SoftNull" OpHelp("r[P1]=NULL"),
- /* 75 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
- /* 76 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
- /* 77 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
- /* 78 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
- /* 79 */ "SCopy" OpHelp("r[P2]=r[P1]"),
- /* 80 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
- /* 81 */ "ResultRow" OpHelp("output=r[P1@P2]"),
- /* 82 */ "CollSeq" OpHelp(""),
- /* 83 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
- /* 84 */ "RealAffinity" OpHelp(""),
- /* 85 */ "Cast" OpHelp("affinity(r[P1])"),
- /* 86 */ "Permutation" OpHelp(""),
- /* 87 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
- /* 88 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
- /* 89 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
- /* 90 */ "Column" OpHelp("r[P3]=PX"),
- /* 91 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
- /* 92 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
- /* 93 */ "Count" OpHelp("r[P2]=count()"),
- /* 94 */ "ReadCookie" OpHelp(""),
- /* 95 */ "SetCookie" OpHelp(""),
- /* 96 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
- /* 97 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
- /* 98 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<>r[P1]"),
- /* 100 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
- /* 101 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
- /* 102 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
- /* 103 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
- /* 104 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
- /* 105 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
- /* 106 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
- /* 107 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
- /* 108 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
- /* 109 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
- /* 110 */ "String8" OpHelp("r[P2]='P4'"),
- /* 111 */ "OpenDup" OpHelp(""),
- /* 112 */ "OpenAutoindex" OpHelp("nColumn=P2"),
- /* 113 */ "OpenEphemeral" OpHelp("nColumn=P2"),
- /* 114 */ "SorterOpen" OpHelp(""),
- /* 115 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
- /* 116 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
- /* 117 */ "Close" OpHelp(""),
- /* 118 */ "ColumnsUsed" OpHelp(""),
- /* 119 */ "SeekHit" OpHelp("seekHit=P2"),
- /* 120 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
- /* 121 */ "NewRowid" OpHelp("r[P2]=rowid"),
- /* 122 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
- /* 123 */ "Delete" OpHelp(""),
- /* 124 */ "ResetCount" OpHelp(""),
- /* 125 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
- /* 126 */ "SorterData" OpHelp("r[P2]=data"),
- /* 127 */ "RowData" OpHelp("r[P2]=data"),
- /* 128 */ "Rowid" OpHelp("r[P2]=rowid"),
- /* 129 */ "NullRow" OpHelp(""),
- /* 130 */ "SeekEnd" OpHelp(""),
- /* 131 */ "SorterInsert" OpHelp("key=r[P2]"),
- /* 132 */ "IdxInsert" OpHelp("key=r[P2]"),
- /* 133 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
- /* 134 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
- /* 135 */ "IdxRowid" OpHelp("r[P2]=rowid"),
- /* 136 */ "Destroy" OpHelp(""),
- /* 137 */ "Clear" OpHelp(""),
- /* 138 */ "ResetSorter" OpHelp(""),
- /* 139 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
- /* 140 */ "SqlExec" OpHelp(""),
- /* 141 */ "ParseSchema" OpHelp(""),
- /* 142 */ "LoadAnalysis" OpHelp(""),
- /* 143 */ "DropTable" OpHelp(""),
- /* 144 */ "DropIndex" OpHelp(""),
- /* 145 */ "Real" OpHelp("r[P2]=P4"),
- /* 146 */ "DropTrigger" OpHelp(""),
- /* 147 */ "IntegrityCk" OpHelp(""),
- /* 148 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
- /* 149 */ "Param" OpHelp(""),
- /* 150 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
- /* 151 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
- /* 152 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
- /* 153 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
- /* 154 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
- /* 155 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
- /* 156 */ "AggValue" OpHelp("r[P3]=value N=P2"),
- /* 157 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
- /* 158 */ "Expire" OpHelp(""),
- /* 159 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
- /* 160 */ "VBegin" OpHelp(""),
- /* 161 */ "VCreate" OpHelp(""),
- /* 162 */ "VDestroy" OpHelp(""),
- /* 163 */ "VOpen" OpHelp(""),
- /* 164 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
- /* 165 */ "VRename" OpHelp(""),
- /* 166 */ "Pagecount" OpHelp(""),
- /* 167 */ "MaxPgcnt" OpHelp(""),
- /* 168 */ "Trace" OpHelp(""),
- /* 169 */ "CursorHint" OpHelp(""),
- /* 170 */ "Noop" OpHelp(""),
- /* 171 */ "Explain" OpHelp(""),
- /* 172 */ "Abortable" OpHelp(""),
- };
- return azName[i];
-}
-#endif
-
-/************** End of opcodes.c *********************************************/
-/************** Begin file os_unix.c *****************************************/
-/*
-** 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 the VFS implementation for unix-like operating systems
-** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
-**
-** There are actually several different VFS implementations in this file.
-** The differences are in the way that file locking is done. The default
-** implementation uses Posix Advisory Locks. Alternative implementations
-** use flock(), dot-files, various proprietary locking schemas, or simply
-** skip locking all together.
-**
-** This source file is organized into divisions where the logic for various
-** subfunctions is contained within the appropriate division. PLEASE
-** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
-** in the correct division and should be clearly labeled.
-**
-** The layout of divisions is as follows:
-**
-** * General-purpose declarations and utility functions.
-** * Unique file ID logic used by VxWorks.
-** * Various locking primitive implementations (all except proxy locking):
-** + for Posix Advisory Locks
-** + for no-op locks
-** + for dot-file locks
-** + for flock() locking
-** + for named semaphore locks (VxWorks only)
-** + for AFP filesystem locks (MacOSX only)
-** * sqlite3_file methods not associated with locking.
-** * Definitions of sqlite3_io_methods objects for all locking
-** methods plus "finder" functions for each locking method.
-** * sqlite3_vfs method implementations.
-** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
-** * Definitions of sqlite3_vfs objects for all locking methods
-** plus implementations of sqlite3_os_init() and sqlite3_os_end().
-*/
-/* #include "sqliteInt.h" */
-#if SQLITE_OS_UNIX /* This file is used on unix only */
-
-/*
-** There are various methods for file locking used for concurrency
-** control:
-**
-** 1. POSIX locking (the default),
-** 2. No locking,
-** 3. Dot-file locking,
-** 4. flock() locking,
-** 5. AFP locking (OSX only),
-** 6. Named POSIX semaphores (VXWorks only),
-** 7. proxy locking. (OSX only)
-**
-** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
-** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
-** selection of the appropriate locking style based on the filesystem
-** where the database is located.
-*/
-#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
-# if defined(__APPLE__)
-# define SQLITE_ENABLE_LOCKING_STYLE 1
-# else
-# define SQLITE_ENABLE_LOCKING_STYLE 0
-# endif
-#endif
-
-/* Use pread() and pwrite() if they are available */
-#if defined(__APPLE__)
-# define HAVE_PREAD 1
-# define HAVE_PWRITE 1
-#endif
-#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
-# undef USE_PREAD
-# define USE_PREAD64 1
-#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
-# undef USE_PREAD64
-# define USE_PREAD 1
-#endif
-
-/*
-** standard include files.
-*/
-#include
-#include
-#include
-#include
-#include
-/* #include */
-#include
-#include
-#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
-# include
-#endif
-
-#if SQLITE_ENABLE_LOCKING_STYLE
-/* # include */
-# include
-# include
-#endif /* SQLITE_ENABLE_LOCKING_STYLE */
-
-#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
- (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
-# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
- && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
-# define HAVE_GETHOSTUUID 1
-# else
-# warning "gethostuuid() is disabled."
-# endif
-#endif
-
-
-#if OS_VXWORKS
-/* # include */
-# include
-# include
-#endif /* OS_VXWORKS */
-
-#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
-# include
-#endif
-
-#ifdef HAVE_UTIME
-# include
-#endif
-
-/*
-** Allowed values of unixFile.fsFlags
-*/
-#define SQLITE_FSFLAGS_IS_MSDOS 0x1
-
-/*
-** If we are to be thread-safe, include the pthreads header.
-*/
-#if SQLITE_THREADSAFE
-/* # include */
-#endif
-
-/*
-** Default permissions when creating a new file
-*/
-#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
-# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
-#endif
-
-/*
-** Default permissions when creating auto proxy dir
-*/
-#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
-# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
-#endif
-
-/*
-** Maximum supported path-length.
-*/
-#define MAX_PATHNAME 512
-
-/*
-** Maximum supported symbolic links
-*/
-#define SQLITE_MAX_SYMLINKS 100
-
-/* Always cast the getpid() return type for compatibility with
-** kernel modules in VxWorks. */
-#define osGetpid(X) (pid_t)getpid()
-
-/*
-** Only set the lastErrno if the error code is a real error and not
-** a normal expected return code of SQLITE_BUSY or SQLITE_OK
-*/
-#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
-
-/* Forward references */
-typedef struct unixShm unixShm; /* Connection shared memory */
-typedef struct unixShmNode unixShmNode; /* Shared memory instance */
-typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
-typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
-
-/*
-** Sometimes, after a file handle is closed by SQLite, the file descriptor
-** cannot be closed immediately. In these cases, instances of the following
-** structure are used to store the file descriptor while waiting for an
-** opportunity to either close or reuse it.
-*/
-struct UnixUnusedFd {
- int fd; /* File descriptor to close */
- int flags; /* Flags this file descriptor was opened with */
- UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
-};
-
-/*
-** The unixFile structure is subclass of sqlite3_file specific to the unix
-** VFS implementations.
-*/
-typedef struct unixFile unixFile;
-struct unixFile {
- sqlite3_io_methods const *pMethod; /* Always the first entry */
- sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
- unixInodeInfo *pInode; /* Info about locks on this inode */
- int h; /* The file descriptor */
- unsigned char eFileLock; /* The type of lock held on this fd */
- unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
- int lastErrno; /* The unix errno from last I/O error */
- void *lockingContext; /* Locking style specific state */
- UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
- const char *zPath; /* Name of the file */
- unixShm *pShm; /* Shared memory segment information */
- int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
-#if SQLITE_MAX_MMAP_SIZE>0
- int nFetchOut; /* Number of outstanding xFetch refs */
- sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
- sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
- sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
- void *pMapRegion; /* Memory mapped region */
-#endif
- int sectorSize; /* Device sector size */
- int deviceCharacteristics; /* Precomputed device characteristics */
-#if SQLITE_ENABLE_LOCKING_STYLE
- int openFlags; /* The flags specified at open() */
-#endif
-#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
- unsigned fsFlags; /* cached details from statfs() */
-#endif
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
- unsigned iBusyTimeout; /* Wait this many millisec on locks */
-#endif
-#if OS_VXWORKS
- struct vxworksFileId *pId; /* Unique file ID */
-#endif
-#ifdef SQLITE_DEBUG
- /* The next group of variables are used to track whether or not the
- ** transaction counter in bytes 24-27 of database files are updated
- ** whenever any part of the database changes. An assertion fault will
- ** occur if a file is updated without also updating the transaction
- ** counter. This test is made to avoid new problems similar to the
- ** one described by ticket #3584.
- */
- unsigned char transCntrChng; /* True if the transaction counter changed */
- unsigned char dbUpdate; /* True if any part of database file changed */
- unsigned char inNormalWrite; /* True if in a normal write operation */
-
-#endif
-
-#ifdef SQLITE_TEST
- /* In test mode, increase the size of this structure a bit so that
- ** it is larger than the struct CrashFile defined in test6.c.
- */
- char aPadding[32];
-#endif
-};
-
-/* This variable holds the process id (pid) from when the xRandomness()
-** method was called. If xOpen() is called from a different process id,
-** indicating that a fork() has occurred, the PRNG will be reset.
-*/
-static pid_t randomnessPid = 0;
-
-/*
-** Allowed values for the unixFile.ctrlFlags bitmask:
-*/
-#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
-#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
-#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
-#ifndef SQLITE_DISABLE_DIRSYNC
-# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
-#else
-# define UNIXFILE_DIRSYNC 0x00
-#endif
-#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
-#define UNIXFILE_DELETE 0x20 /* Delete on close */
-#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
-#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
-
-/*
-** Include code that is common to all os_*.c files
-*/
-/************** Include os_common.h in the middle of os_unix.c ***************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 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.
-*/
-#ifndef _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.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing. Normally turned off. Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 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.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_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 (defined(__GNUC__) || defined(_MSC_VER)) && \
- (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
- #if defined(__GNUC__)
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned int lo, hi;
- __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
- return (sqlite_uint64)hi << 32 | lo;
- }
-
- #elif defined(_MSC_VER)
-
- __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
- __asm {
- rdtsc
- ret ; return value at EDX:EAX
- }
- }
-
- #endif
-
-#elif (defined(__GNUC__) && defined(__x86_64__))
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned long val;
- __asm__ __volatile__ ("rdtsc" : "=A" (val));
- return val;
- }
-
-#elif (defined(__GNUC__) && defined(__ppc__))
-
- __inline__ sqlite_uint64 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.
- */
-SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START g_start=sqlite3Hwtime()
-#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED ((sqlite_uint64)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 defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE) \
- if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
- || sqlite3_io_error_pending-- == 1 ) \
- { local_ioerr(); CODE; }
-static void local_ioerr(){
- IOTRACE(("IOERR\n"));
- sqlite3_io_error_hit++;
- if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#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--; \
- } \
- }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X) sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in os_unix.c ********************/
-
-/*
-** Define various macros that are missing from some systems.
-*/
-#ifndef O_LARGEFILE
-# define O_LARGEFILE 0
-#endif
-#ifdef SQLITE_DISABLE_LFS
-# undef O_LARGEFILE
-# define O_LARGEFILE 0
-#endif
-#ifndef O_NOFOLLOW
-# define O_NOFOLLOW 0
-#endif
-#ifndef O_BINARY
-# define O_BINARY 0
-#endif
-
-/*
-** The threadid macro resolves to the thread-id or to 0. Used for
-** testing and debugging only.
-*/
-#if SQLITE_THREADSAFE
-#define threadid pthread_self()
-#else
-#define threadid 0
-#endif
-
-/*
-** HAVE_MREMAP defaults to true on Linux and false everywhere else.
-*/
-#if !defined(HAVE_MREMAP)
-# if defined(__linux__) && defined(_GNU_SOURCE)
-# define HAVE_MREMAP 1
-# else
-# define HAVE_MREMAP 0
-# endif
-#endif
-
-/*
-** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
-** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
-*/
-#ifdef __ANDROID__
-# define lseek lseek64
-#endif
-
-#ifdef __linux__
-/*
-** Linux-specific IOCTL magic numbers used for controlling F2FS
-*/
-#define F2FS_IOCTL_MAGIC 0xf5
-#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
-#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
-#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
-#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
-#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
-#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
-#endif /* __linux__ */
-
-
-/*
-** Different Unix systems declare open() in different ways. Same use
-** open(const char*,int,mode_t). Others use open(const char*,int,...).
-** The difference is important when using a pointer to the function.
-**
-** The safest way to deal with the problem is to always use this wrapper
-** which always has the same well-defined interface.
-*/
-static int posixOpen(const char *zFile, int flags, int mode){
- return open(zFile, flags, mode);
-}
-
-/* Forward reference */
-static int openDirectory(const char*, int*);
-static int unixGetpagesize(void);
-
-/*
-** Many system calls are accessed through pointer-to-functions so that
-** they may be overridden at runtime to facilitate fault injection during
-** testing and sandboxing. The following array holds the names and pointers
-** to all overrideable system calls.
-*/
-static struct unix_syscall {
- const char *zName; /* Name of the system call */
- sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
- sqlite3_syscall_ptr pDefault; /* Default value */
-} aSyscall[] = {
- { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
-#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
-
- { "close", (sqlite3_syscall_ptr)close, 0 },
-#define osClose ((int(*)(int))aSyscall[1].pCurrent)
-
- { "access", (sqlite3_syscall_ptr)access, 0 },
-#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
-
- { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
-#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
-
- { "stat", (sqlite3_syscall_ptr)stat, 0 },
-#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
-
-/*
-** The DJGPP compiler environment looks mostly like Unix, but it
-** lacks the fcntl() system call. So redefine fcntl() to be something
-** that always succeeds. This means that locking does not occur under
-** DJGPP. But it is DOS - what did you expect?
-*/
-#ifdef __DJGPP__
- { "fstat", 0, 0 },
-#define osFstat(a,b,c) 0
-#else
- { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
-#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
-#endif
-
- { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
-#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
-
- { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
-#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
-
- { "read", (sqlite3_syscall_ptr)read, 0 },
-#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
-
-#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
- { "pread", (sqlite3_syscall_ptr)pread, 0 },
-#else
- { "pread", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
-
-#if defined(USE_PREAD64)
- { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
-#else
- { "pread64", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
-
- { "write", (sqlite3_syscall_ptr)write, 0 },
-#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
-
-#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
- { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
-#else
- { "pwrite", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
- aSyscall[12].pCurrent)
-
-#if defined(USE_PREAD64)
- { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
-#else
- { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
- aSyscall[13].pCurrent)
-
- { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
-#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
-
-#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
- { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
-#else
- { "fallocate", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
-
- { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
-#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
-
- { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
-#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
-
- { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
-#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
-
- { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
-#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
-
-#if defined(HAVE_FCHOWN)
- { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
-#else
- { "fchown", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
-
-#if defined(HAVE_FCHOWN)
- { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
-#else
- { "geteuid", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
-
-#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
- { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
-#else
- { "mmap", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
-
-#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
- { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
-#else
- { "munmap", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
-
-#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
- { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
-#else
- { "mremap", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
-
-#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
- { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
-#else
- { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
-
-#if defined(HAVE_READLINK)
- { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
-#else
- { "readlink", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
-
-#if defined(HAVE_LSTAT)
- { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
-#else
- { "lstat", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
-
-#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
-# ifdef __ANDROID__
- { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
-# else
- { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
-# endif
-#else
- { "ioctl", (sqlite3_syscall_ptr)0, 0 },
-#endif
-#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
-
-}; /* End of the overrideable system calls */
-
-
-/*
-** On some systems, calls to fchown() will trigger a message in a security
-** log if they come from non-root processes. So avoid calling fchown() if
-** we are not running as root.
-*/
-static int robustFchown(int fd, uid_t uid, gid_t gid){
-#if defined(HAVE_FCHOWN)
- return osGeteuid() ? 0 : osFchown(fd,uid,gid);
-#else
- return 0;
-#endif
-}
-
-/*
-** This is the xSetSystemCall() method of sqlite3_vfs for all of the
-** "unix" VFSes. Return SQLITE_OK opon successfully updating the
-** system call pointer, or SQLITE_NOTFOUND if there is no configurable
-** system call named zName.
-*/
-static int unixSetSystemCall(
- sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
- const char *zName, /* Name of system call to override */
- sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
-){
- unsigned int i;
- int rc = SQLITE_NOTFOUND;
-
- UNUSED_PARAMETER(pNotUsed);
- if( zName==0 ){
- /* If no zName is given, restore all system calls to their default
- ** settings and return NULL
- */
- rc = SQLITE_OK;
- for(i=0; i=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
- osClose(fd);
- sqlite3_log(SQLITE_WARNING,
- "attempt to open \"%s\" as file descriptor %d", z, fd);
- fd = -1;
- if( osOpen("/dev/null", f, m)<0 ) break;
- }
- if( fd>=0 ){
- if( m!=0 ){
- struct stat statbuf;
- if( osFstat(fd, &statbuf)==0
- && statbuf.st_size==0
- && (statbuf.st_mode&0777)!=m
- ){
- osFchmod(fd, m);
- }
- }
-#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
- osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
-#endif
- }
- return fd;
-}
-
-/*
-** Helper functions to obtain and relinquish the global mutex. The
-** global mutex is used to protect the unixInodeInfo and
-** vxworksFileId objects used by this file, all of which may be
-** shared by multiple threads.
-**
-** Function unixMutexHeld() is used to assert() that the global mutex
-** is held when required. This function is only used as part of assert()
-** statements. e.g.
-**
-** unixEnterMutex()
-** assert( unixMutexHeld() );
-** unixEnterLeave()
-**
-** To prevent deadlock, the global unixBigLock must must be acquired
-** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
-** OK to get the pLockMutex without holding unixBigLock first, but if
-** that happens, the unixBigLock mutex must not be acquired until after
-** pLockMutex is released.
-**
-** OK: enter(unixBigLock), enter(pLockInfo)
-** OK: enter(unixBigLock)
-** OK: enter(pLockInfo)
-** ERROR: enter(pLockInfo), enter(unixBigLock)
-*/
-static sqlite3_mutex *unixBigLock = 0;
-static void unixEnterMutex(void){
- assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
- sqlite3_mutex_enter(unixBigLock);
-}
-static void unixLeaveMutex(void){
- assert( sqlite3_mutex_held(unixBigLock) );
- sqlite3_mutex_leave(unixBigLock);
-}
-#ifdef SQLITE_DEBUG
-static int unixMutexHeld(void) {
- return sqlite3_mutex_held(unixBigLock);
-}
-#endif
-
-
-#ifdef SQLITE_HAVE_OS_TRACE
-/*
-** Helper function for printing out trace information from debugging
-** binaries. This returns the string representation of the supplied
-** integer lock-type.
-*/
-static const char *azFileLock(int eFileLock){
- switch( eFileLock ){
- case NO_LOCK: return "NONE";
- case SHARED_LOCK: return "SHARED";
- case RESERVED_LOCK: return "RESERVED";
- case PENDING_LOCK: return "PENDING";
- case EXCLUSIVE_LOCK: return "EXCLUSIVE";
- }
- return "ERROR";
-}
-#endif
-
-#ifdef SQLITE_LOCK_TRACE
-/*
-** Print out information about all locking operations.
-**
-** This routine is used for troubleshooting locks on multithreaded
-** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
-** command-line option on the compiler. This code is normally
-** turned off.
-*/
-static int lockTrace(int fd, int op, struct flock *p){
- char *zOpName, *zType;
- int s;
- int savedErrno;
- if( op==F_GETLK ){
- zOpName = "GETLK";
- }else if( op==F_SETLK ){
- zOpName = "SETLK";
- }else{
- s = osFcntl(fd, op, p);
- sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
- return s;
- }
- if( p->l_type==F_RDLCK ){
- zType = "RDLCK";
- }else if( p->l_type==F_WRLCK ){
- zType = "WRLCK";
- }else if( p->l_type==F_UNLCK ){
- zType = "UNLCK";
- }else{
- assert( 0 );
- }
- assert( p->l_whence==SEEK_SET );
- s = osFcntl(fd, op, p);
- savedErrno = errno;
- sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
- threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
- (int)p->l_pid, s);
- if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
- struct flock l2;
- l2 = *p;
- osFcntl(fd, F_GETLK, &l2);
- if( l2.l_type==F_RDLCK ){
- zType = "RDLCK";
- }else if( l2.l_type==F_WRLCK ){
- zType = "WRLCK";
- }else if( l2.l_type==F_UNLCK ){
- zType = "UNLCK";
- }else{
- assert( 0 );
- }
- sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
- zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
- }
- errno = savedErrno;
- return s;
-}
-#undef osFcntl
-#define osFcntl lockTrace
-#endif /* SQLITE_LOCK_TRACE */
-
-/*
-** Retry ftruncate() calls that fail due to EINTR
-**
-** All calls to ftruncate() within this file should be made through
-** this wrapper. On the Android platform, bypassing the logic below
-** could lead to a corrupt database.
-*/
-static int robust_ftruncate(int h, sqlite3_int64 sz){
- int rc;
-#ifdef __ANDROID__
- /* On Android, ftruncate() always uses 32-bit offsets, even if
- ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
- ** truncate a file to any size larger than 2GiB. Silently ignore any
- ** such attempts. */
- if( sz>(sqlite3_int64)0x7FFFFFFF ){
- rc = SQLITE_OK;
- }else
-#endif
- do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
- return rc;
-}
-
-/*
-** This routine translates a standard POSIX errno code into something
-** useful to the clients of the sqlite3 functions. Specifically, it is
-** intended to translate a variety of "try again" errors into SQLITE_BUSY
-** and a variety of "please close the file descriptor NOW" errors into
-** SQLITE_IOERR
-**
-** Errors during initialization of locks, or file system support for locks,
-** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
-*/
-static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
- assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
- (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
- (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
- (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
- switch (posixError) {
- case EACCES:
- case EAGAIN:
- case ETIMEDOUT:
- case EBUSY:
- case EINTR:
- case ENOLCK:
- /* random NFS retry error, unless during file system support
- * introspection, in which it actually means what it says */
- return SQLITE_BUSY;
-
- case EPERM:
- return SQLITE_PERM;
-
- default:
- return sqliteIOErr;
- }
-}
-
-
-/******************************************************************************
-****************** Begin Unique File ID Utility Used By VxWorks ***************
-**
-** On most versions of unix, we can get a unique ID for a file by concatenating
-** the device number and the inode number. But this does not work on VxWorks.
-** On VxWorks, a unique file id must be based on the canonical filename.
-**
-** A pointer to an instance of the following structure can be used as a
-** unique file ID in VxWorks. Each instance of this structure contains
-** a copy of the canonical filename. There is also a reference count.
-** The structure is reclaimed when the number of pointers to it drops to
-** zero.
-**
-** There are never very many files open at one time and lookups are not
-** a performance-critical path, so it is sufficient to put these
-** structures on a linked list.
-*/
-struct vxworksFileId {
- struct vxworksFileId *pNext; /* Next in a list of them all */
- int nRef; /* Number of references to this one */
- int nName; /* Length of the zCanonicalName[] string */
- char *zCanonicalName; /* Canonical filename */
-};
-
-#if OS_VXWORKS
-/*
-** All unique filenames are held on a linked list headed by this
-** variable:
-*/
-static struct vxworksFileId *vxworksFileList = 0;
-
-/*
-** Simplify a filename into its canonical form
-** by making the following changes:
-**
-** * removing any trailing and duplicate /
-** * convert /./ into just /
-** * convert /A/../ where A is any simple name into just /
-**
-** Changes are made in-place. Return the new name length.
-**
-** The original filename is in z[0..n-1]. Return the number of
-** characters in the simplified name.
-*/
-static int vxworksSimplifyName(char *z, int n){
- int i, j;
- while( n>1 && z[n-1]=='/' ){ n--; }
- for(i=j=0; i0 && z[j-1]!='/' ){ j--; }
- if( j>0 ){ j--; }
- i += 2;
- continue;
- }
- }
- z[j++] = z[i];
- }
- z[j] = 0;
- return j;
-}
-
-/*
-** Find a unique file ID for the given absolute pathname. Return
-** a pointer to the vxworksFileId object. This pointer is the unique
-** file ID.
-**
-** The nRef field of the vxworksFileId object is incremented before
-** the object is returned. A new vxworksFileId object is created
-** and added to the global list if necessary.
-**
-** If a memory allocation error occurs, return NULL.
-*/
-static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
- struct vxworksFileId *pNew; /* search key and new file ID */
- struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
- int n; /* Length of zAbsoluteName string */
-
- assert( zAbsoluteName[0]=='/' );
- n = (int)strlen(zAbsoluteName);
- pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
- if( pNew==0 ) return 0;
- pNew->zCanonicalName = (char*)&pNew[1];
- memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
- n = vxworksSimplifyName(pNew->zCanonicalName, n);
-
- /* Search for an existing entry that matching the canonical name.
- ** If found, increment the reference count and return a pointer to
- ** the existing file ID.
- */
- unixEnterMutex();
- for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
- if( pCandidate->nName==n
- && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
- ){
- sqlite3_free(pNew);
- pCandidate->nRef++;
- unixLeaveMutex();
- return pCandidate;
- }
- }
-
- /* No match was found. We will make a new file ID */
- pNew->nRef = 1;
- pNew->nName = n;
- pNew->pNext = vxworksFileList;
- vxworksFileList = pNew;
- unixLeaveMutex();
- return pNew;
-}
-
-/*
-** Decrement the reference count on a vxworksFileId object. Free
-** the object when the reference count reaches zero.
-*/
-static void vxworksReleaseFileId(struct vxworksFileId *pId){
- unixEnterMutex();
- assert( pId->nRef>0 );
- pId->nRef--;
- if( pId->nRef==0 ){
- struct vxworksFileId **pp;
- for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
- assert( *pp==pId );
- *pp = pId->pNext;
- sqlite3_free(pId);
- }
- unixLeaveMutex();
-}
-#endif /* OS_VXWORKS */
-/*************** End of Unique File ID Utility Used By VxWorks ****************
-******************************************************************************/
-
-
-/******************************************************************************
-*************************** Posix Advisory Locking ****************************
-**
-** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
-** section 6.5.2.2 lines 483 through 490 specify that when a process
-** sets or clears a lock, that operation overrides any prior locks set
-** by the same process. It does not explicitly say so, but this implies
-** that it overrides locks set by the same process using a different
-** file descriptor. Consider this test case:
-**
-** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
-** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
-**
-** Suppose ./file1 and ./file2 are really the same file (because
-** one is a hard or symbolic link to the other) then if you set
-** an exclusive lock on fd1, then try to get an exclusive lock
-** on fd2, it works. I would have expected the second lock to
-** fail since there was already a lock on the file due to fd1.
-** But not so. Since both locks came from the same process, the
-** second overrides the first, even though they were on different
-** file descriptors opened on different file names.
-**
-** This means that we cannot use POSIX locks to synchronize file access
-** among competing threads of the same process. POSIX locks will work fine
-** to synchronize access for threads in separate processes, but not
-** threads within the same process.
-**
-** To work around the problem, SQLite has to manage file locks internally
-** on its own. Whenever a new database is opened, we have to find the
-** specific inode of the database file (the inode is determined by the
-** st_dev and st_ino fields of the stat structure that fstat() fills in)
-** and check for locks already existing on that inode. When locks are
-** created or removed, we have to look at our own internal record of the
-** locks to see if another thread has previously set a lock on that same
-** inode.
-**
-** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
-** For VxWorks, we have to use the alternative unique ID system based on
-** canonical filename and implemented in the previous division.)
-**
-** The sqlite3_file structure for POSIX is no longer just an integer file
-** descriptor. It is now a structure that holds the integer file
-** descriptor and a pointer to a structure that describes the internal
-** locks on the corresponding inode. There is one locking structure
-** per inode, so if the same inode is opened twice, both unixFile structures
-** point to the same locking structure. The locking structure keeps
-** a reference count (so we will know when to delete it) and a "cnt"
-** field that tells us its internal lock status. cnt==0 means the
-** file is unlocked. cnt==-1 means the file has an exclusive lock.
-** cnt>0 means there are cnt shared locks on the file.
-**
-** Any attempt to lock or unlock a file first checks the locking
-** structure. The fcntl() system call is only invoked to set a
-** POSIX lock if the internal lock structure transitions between
-** a locked and an unlocked state.
-**
-** But wait: there are yet more problems with POSIX advisory locks.
-**
-** If you close a file descriptor that points to a file that has locks,
-** all locks on that file that are owned by the current process are
-** released. To work around this problem, each unixInodeInfo object
-** maintains a count of the number of pending locks on tha inode.
-** When an attempt is made to close an unixFile, if there are
-** other unixFile open on the same inode that are holding locks, the call
-** to close() the file descriptor is deferred until all of the locks clear.
-** The unixInodeInfo structure keeps a list of file descriptors that need to
-** be closed and that list is walked (and cleared) when the last lock
-** clears.
-**
-** Yet another problem: LinuxThreads do not play well with posix locks.
-**
-** Many older versions of linux use the LinuxThreads library which is
-** not posix compliant. Under LinuxThreads, a lock created by thread
-** A cannot be modified or overridden by a different thread B.
-** Only thread A can modify the lock. Locking behavior is correct
-** if the appliation uses the newer Native Posix Thread Library (NPTL)
-** on linux - with NPTL a lock created by thread A can override locks
-** in thread B. But there is no way to know at compile-time which
-** threading library is being used. So there is no way to know at
-** compile-time whether or not thread A can override locks on thread B.
-** One has to do a run-time check to discover the behavior of the
-** current process.
-**
-** SQLite used to support LinuxThreads. But support for LinuxThreads
-** was dropped beginning with version 3.7.0. SQLite will still work with
-** LinuxThreads provided that (1) there is no more than one connection
-** per database file in the same process and (2) database connections
-** do not move across threads.
-*/
-
-/*
-** An instance of the following structure serves as the key used
-** to locate a particular unixInodeInfo object.
-*/
-struct unixFileId {
- dev_t dev; /* Device number */
-#if OS_VXWORKS
- struct vxworksFileId *pId; /* Unique file ID for vxworks. */
-#else
- /* We are told that some versions of Android contain a bug that
- ** sizes ino_t at only 32-bits instead of 64-bits. (See
- ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
- ** To work around this, always allocate 64-bits for the inode number.
- ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
- ** but that should not be a big deal. */
- /* WAS: ino_t ino; */
- u64 ino; /* Inode number */
-#endif
-};
-
-/*
-** An instance of the following structure is allocated for each open
-** inode.
-**
-** A single inode can have multiple file descriptors, so each unixFile
-** structure contains a pointer to an instance of this object and this
-** object keeps a count of the number of unixFile pointing to it.
-**
-** Mutex rules:
-**
-** (1) Only the pLockMutex mutex must be held in order to read or write
-** any of the locking fields:
-** nShared, nLock, eFileLock, bProcessLock, pUnused
-**
-** (2) When nRef>0, then the following fields are unchanging and can
-** be read (but not written) without holding any mutex:
-** fileId, pLockMutex
-**
-** (3) With the exceptions above, all the fields may only be read
-** or written while holding the global unixBigLock mutex.
-**
-** Deadlock prevention: The global unixBigLock mutex may not
-** be acquired while holding the pLockMutex mutex. If both unixBigLock
-** and pLockMutex are needed, then unixBigLock must be acquired first.
-*/
-struct unixInodeInfo {
- struct unixFileId fileId; /* The lookup key */
- sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
- int nShared; /* Number of SHARED locks held */
- int nLock; /* Number of outstanding file locks */
- unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
- unsigned char bProcessLock; /* An exclusive process lock is held */
- UnixUnusedFd *pUnused; /* Unused file descriptors to close */
- int nRef; /* Number of pointers to this structure */
- unixShmNode *pShmNode; /* Shared memory associated with this inode */
- unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
- unixInodeInfo *pPrev; /* .... doubly linked */
-#if SQLITE_ENABLE_LOCKING_STYLE
- unsigned long long sharedByte; /* for AFP simulated shared lock */
-#endif
-#if OS_VXWORKS
- sem_t *pSem; /* Named POSIX semaphore */
- char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
-#endif
-};
-
-/*
-** A lists of all unixInodeInfo objects.
-**
-** Must hold unixBigLock in order to read or write this variable.
-*/
-static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
-
-#ifdef SQLITE_DEBUG
-/*
-** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
-** This routine is used only within assert() to help verify correct mutex
-** usage.
-*/
-int unixFileMutexHeld(unixFile *pFile){
- assert( pFile->pInode );
- return sqlite3_mutex_held(pFile->pInode->pLockMutex);
-}
-int unixFileMutexNotheld(unixFile *pFile){
- assert( pFile->pInode );
- return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
-}
-#endif
-
-/*
-**
-** This function - unixLogErrorAtLine(), is only ever called via the macro
-** unixLogError().
-**
-** It is invoked after an error occurs in an OS function and errno has been
-** set. It logs a message using sqlite3_log() containing the current value of
-** errno and, if possible, the human-readable equivalent from strerror() or
-** strerror_r().
-**
-** 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 (e.g. "unlink", "open") and the associated file-system path,
-** if any.
-*/
-#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
-static int unixLogErrorAtLine(
- int errcode, /* SQLite error code */
- const char *zFunc, /* Name of OS function that failed */
- const char *zPath, /* File path associated with error */
- int iLine /* Source line number where error occurred */
-){
- char *zErr; /* Message from strerror() or equivalent */
- int iErrno = errno; /* Saved syscall error number */
-
- /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
- ** the strerror() function to obtain the human-readable error message
- ** equivalent to errno. Otherwise, use strerror_r().
- */
-#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
- char aErr[80];
- memset(aErr, 0, sizeof(aErr));
- zErr = aErr;
-
- /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
- ** assume that the system provides the GNU version of strerror_r() that
- ** returns a pointer to a buffer containing the error message. That pointer
- ** may point to aErr[], or it may point to some static storage somewhere.
- ** Otherwise, assume that the system provides the POSIX version of
- ** strerror_r(), which always writes an error message into aErr[].
- **
- ** If the code incorrectly assumes that it is the POSIX version that is
- ** available, the error message will often be an empty string. Not a
- ** huge problem. Incorrectly concluding that the GNU version is available
- ** could lead to a segfault though.
- */
-#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
- zErr =
-# endif
- strerror_r(iErrno, aErr, sizeof(aErr)-1);
-
-#elif SQLITE_THREADSAFE
- /* This is a threadsafe build, but strerror_r() is not available. */
- zErr = "";
-#else
- /* Non-threadsafe build, use strerror(). */
- zErr = strerror(iErrno);
-#endif
-
- if( zPath==0 ) zPath = "";
- sqlite3_log(errcode,
- "os_unix.c:%d: (%d) %s(%s) - %s",
- iLine, iErrno, zFunc, zPath, zErr
- );
-
- return errcode;
-}
-
-/*
-** Close a file descriptor.
-**
-** We assume that close() almost always works, since it is only in a
-** very sick application or on a very sick platform that it might fail.
-** If it does fail, simply leak the file descriptor, but do log the
-** error.
-**
-** Note that it is not safe to retry close() after EINTR since the
-** file descriptor might have already been reused by another thread.
-** So we don't even try to recover from an EINTR. Just log the error
-** and move on.
-*/
-static void robust_close(unixFile *pFile, int h, int lineno){
- if( osClose(h) ){
- unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
- pFile ? pFile->zPath : 0, lineno);
- }
-}
-
-/*
-** Set the pFile->lastErrno. Do this in a subroutine as that provides
-** a convenient place to set a breakpoint.
-*/
-static void storeLastErrno(unixFile *pFile, int error){
- pFile->lastErrno = error;
-}
-
-/*
-** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
-*/
-static void closePendingFds(unixFile *pFile){
- unixInodeInfo *pInode = pFile->pInode;
- UnixUnusedFd *p;
- UnixUnusedFd *pNext;
- assert( unixFileMutexHeld(pFile) );
- for(p=pInode->pUnused; p; p=pNext){
- pNext = p->pNext;
- robust_close(pFile, p->fd, __LINE__);
- sqlite3_free(p);
- }
- pInode->pUnused = 0;
-}
-
-/*
-** Release a unixInodeInfo structure previously allocated by findInodeInfo().
-**
-** The global mutex must be held when this routine is called, but the mutex
-** on the inode being deleted must NOT be held.
-*/
-static void releaseInodeInfo(unixFile *pFile){
- unixInodeInfo *pInode = pFile->pInode;
- assert( unixMutexHeld() );
- assert( unixFileMutexNotheld(pFile) );
- if( ALWAYS(pInode) ){
- pInode->nRef--;
- if( pInode->nRef==0 ){
- assert( pInode->pShmNode==0 );
- sqlite3_mutex_enter(pInode->pLockMutex);
- closePendingFds(pFile);
- sqlite3_mutex_leave(pInode->pLockMutex);
- if( pInode->pPrev ){
- assert( pInode->pPrev->pNext==pInode );
- pInode->pPrev->pNext = pInode->pNext;
- }else{
- assert( inodeList==pInode );
- inodeList = pInode->pNext;
- }
- if( pInode->pNext ){
- assert( pInode->pNext->pPrev==pInode );
- pInode->pNext->pPrev = pInode->pPrev;
- }
- sqlite3_mutex_free(pInode->pLockMutex);
- sqlite3_free(pInode);
- }
- }
-}
-
-/*
-** Given a file descriptor, locate the unixInodeInfo object that
-** describes that file descriptor. Create a new one if necessary. The
-** return value might be uninitialized if an error occurs.
-**
-** The global mutex must held when calling this routine.
-**
-** Return an appropriate error code.
-*/
-static int findInodeInfo(
- unixFile *pFile, /* Unix file with file desc used in the key */
- unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
-){
- int rc; /* System call return code */
- int fd; /* The file descriptor for pFile */
- struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
- struct stat statbuf; /* Low-level file information */
- unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
-
- assert( unixMutexHeld() );
-
- /* Get low-level information about the file that we can used to
- ** create a unique name for the file.
- */
- fd = pFile->h;
- rc = osFstat(fd, &statbuf);
- if( rc!=0 ){
- storeLastErrno(pFile, errno);
-#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
- if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
-#endif
- return SQLITE_IOERR;
- }
-
-#ifdef __APPLE__
- /* On OS X on an msdos filesystem, the inode number is reported
- ** incorrectly for zero-size files. See ticket #3260. To work
- ** around this problem (we consider it a bug in OS X, not SQLite)
- ** we always increase the file size to 1 by writing a single byte
- ** prior to accessing the inode number. The one byte written is
- ** an ASCII 'S' character which also happens to be the first byte
- ** in the header of every SQLite database. In this way, if there
- ** is a race condition such that another thread has already populated
- ** the first page of the database, no damage is done.
- */
- if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
- do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
- if( rc!=1 ){
- storeLastErrno(pFile, errno);
- return SQLITE_IOERR;
- }
- rc = osFstat(fd, &statbuf);
- if( rc!=0 ){
- storeLastErrno(pFile, errno);
- return SQLITE_IOERR;
- }
- }
-#endif
-
- memset(&fileId, 0, sizeof(fileId));
- fileId.dev = statbuf.st_dev;
-#if OS_VXWORKS
- fileId.pId = pFile->pId;
-#else
- fileId.ino = (u64)statbuf.st_ino;
-#endif
- assert( unixMutexHeld() );
- pInode = inodeList;
- while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
- pInode = pInode->pNext;
- }
- if( pInode==0 ){
- pInode = sqlite3_malloc64( sizeof(*pInode) );
- if( pInode==0 ){
- return SQLITE_NOMEM_BKPT;
- }
- memset(pInode, 0, sizeof(*pInode));
- memcpy(&pInode->fileId, &fileId, sizeof(fileId));
- if( sqlite3GlobalConfig.bCoreMutex ){
- pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
- if( pInode->pLockMutex==0 ){
- sqlite3_free(pInode);
- return SQLITE_NOMEM_BKPT;
- }
- }
- pInode->nRef = 1;
- assert( unixMutexHeld() );
- pInode->pNext = inodeList;
- pInode->pPrev = 0;
- if( inodeList ) inodeList->pPrev = pInode;
- inodeList = pInode;
- }else{
- pInode->nRef++;
- }
- *ppInode = pInode;
- return SQLITE_OK;
-}
-
-/*
-** Return TRUE if pFile has been renamed or unlinked since it was first opened.
-*/
-static int fileHasMoved(unixFile *pFile){
-#if OS_VXWORKS
- return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
-#else
- struct stat buf;
- return pFile->pInode!=0 &&
- (osStat(pFile->zPath, &buf)!=0
- || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
-#endif
-}
-
-
-/*
-** Check a unixFile that is a database. Verify the following:
-**
-** (1) There is exactly one hard link on the file
-** (2) The file is not a symbolic link
-** (3) The file has not been renamed or unlinked
-**
-** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
-*/
-static void verifyDbFile(unixFile *pFile){
- struct stat buf;
- int rc;
-
- /* These verifications occurs for the main database only */
- if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
-
- rc = osFstat(pFile->h, &buf);
- if( rc!=0 ){
- sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
- return;
- }
- if( buf.st_nlink==0 ){
- sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
- return;
- }
- if( buf.st_nlink>1 ){
- sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
- return;
- }
- if( fileHasMoved(pFile) ){
- sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
- return;
- }
-}
-
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-*/
-static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
- int rc = SQLITE_OK;
- int reserved = 0;
- unixFile *pFile = (unixFile*)id;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-
- assert( pFile );
- assert( pFile->eFileLock<=SHARED_LOCK );
- sqlite3_mutex_enter(pFile->pInode->pLockMutex);
-
- /* Check if a thread in this process holds such a lock */
- if( pFile->pInode->eFileLock>SHARED_LOCK ){
- reserved = 1;
- }
-
- /* Otherwise see if some other process holds it.
- */
-#ifndef __DJGPP__
- if( !reserved && !pFile->pInode->bProcessLock ){
- struct flock lock;
- lock.l_whence = SEEK_SET;
- lock.l_start = RESERVED_BYTE;
- lock.l_len = 1;
- lock.l_type = F_WRLCK;
- if( osFcntl(pFile->h, F_GETLK, &lock) ){
- rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
- storeLastErrno(pFile, errno);
- } else if( lock.l_type!=F_UNLCK ){
- reserved = 1;
- }
- }
-#endif
-
- sqlite3_mutex_leave(pFile->pInode->pLockMutex);
- OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
-
- *pResOut = reserved;
- return rc;
-}
-
-/*
-** Set a posix-advisory-lock.
-**
-** There are two versions of this routine. If compiled with
-** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
-** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
-** value is set, then it is the number of milliseconds to wait before
-** failing the lock. The iBusyTimeout value is always reset back to
-** zero on each call.
-**
-** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
-** attempt to set the lock.
-*/
-#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
-# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
-#else
-static int osSetPosixAdvisoryLock(
- int h, /* The file descriptor on which to take the lock */
- struct flock *pLock, /* The description of the lock */
- unixFile *pFile /* Structure holding timeout value */
-){
- int rc = osFcntl(h,F_SETLK,pLock);
- while( rc<0 && pFile->iBusyTimeout>0 ){
- /* On systems that support some kind of blocking file lock with a timeout,
- ** make appropriate changes here to invoke that blocking file lock. On
- ** generic posix, however, there is no such API. So we simply try the
- ** lock once every millisecond until either the timeout expires, or until
- ** the lock is obtained. */
- usleep(1000);
- rc = osFcntl(h,F_SETLK,pLock);
- pFile->iBusyTimeout--;
- }
- return rc;
-}
-#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
-
-
-/*
-** Attempt to set a system-lock on the file pFile. The lock is
-** described by pLock.
-**
-** If the pFile was opened read/write from unix-excl, then the only lock
-** ever obtained is an exclusive lock, and it is obtained exactly once
-** the first time any lock is attempted. All subsequent system locking
-** operations become no-ops. Locking operations still happen internally,
-** in order to coordinate access between separate database connections
-** within this process, but all of that is handled in memory and the
-** operating system does not participate.
-**
-** This function is a pass-through to fcntl(F_SETLK) if pFile is using
-** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
-** and is read-only.
-**
-** Zero is returned if the call completes successfully, or -1 if a call
-** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
-*/
-static int unixFileLock(unixFile *pFile, struct flock *pLock){
- int rc;
- unixInodeInfo *pInode = pFile->pInode;
- assert( pInode!=0 );
- assert( sqlite3_mutex_held(pInode->pLockMutex) );
- if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
- if( pInode->bProcessLock==0 ){
- struct flock lock;
- assert( pInode->nLock==0 );
- lock.l_whence = SEEK_SET;
- lock.l_start = SHARED_FIRST;
- lock.l_len = SHARED_SIZE;
- lock.l_type = F_WRLCK;
- rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
- if( rc<0 ) return rc;
- pInode->bProcessLock = 1;
- pInode->nLock++;
- }else{
- rc = 0;
- }
- }else{
- rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
- }
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-*/
-static int unixLock(sqlite3_file *id, int eFileLock){
- /* The following describes the implementation of the various locks and
- ** lock transitions in terms of the POSIX advisory shared and exclusive
- ** lock primitives (called read-locks and write-locks below, to avoid
- ** confusion with SQLite lock names). The algorithms are complicated
- ** slightly in order to be compatible with Windows95 systems simultaneously
- ** accessing the same database file, in case that is ever required.
- **
- ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
- ** byte', each single bytes at well known offsets, and the 'shared byte
- ** range', a range of 510 bytes at a well known offset.
- **
- ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
- ** byte'. If this is successful, 'shared byte range' is read-locked
- ** and the lock on the 'pending byte' released. (Legacy note: When
- ** SQLite was first developed, Windows95 systems were still very common,
- ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
- ** single randomly selected by from the 'shared byte range' is locked.
- ** Windows95 is now pretty much extinct, but this work-around for the
- ** lack of shared-locks on Windows95 lives on, for backwards
- ** compatibility.)
- **
- ** A process may only obtain a RESERVED lock after it has a SHARED lock.
- ** A RESERVED lock is implemented by grabbing a write-lock on the
- ** 'reserved byte'.
- **
- ** A process may only obtain a PENDING lock after it has obtained a
- ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
- ** on the 'pending byte'. This ensures that no new SHARED locks can be
- ** obtained, but existing SHARED locks are allowed to persist. A process
- ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
- ** This property is used by the algorithm for rolling back a journal file
- ** after a crash.
- **
- ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
- ** implemented by obtaining a write-lock on the entire 'shared byte
- ** range'. Since all other locks require a read-lock on one of the bytes
- ** within this range, this ensures that no other locks are held on the
- ** database.
- */
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile*)id;
- unixInodeInfo *pInode;
- struct flock lock;
- int tErrno = 0;
-
- assert( pFile );
- OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
- azFileLock(eFileLock), azFileLock(pFile->eFileLock),
- azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
- osGetpid(0)));
-
- /* If there is already a lock of this type or more restrictive on the
- ** unixFile, do nothing. Don't use the end_lock: exit path, as
- ** unixEnterMutex() hasn't been called yet.
- */
- if( pFile->eFileLock>=eFileLock ){
- OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
- azFileLock(eFileLock)));
- return SQLITE_OK;
- }
-
- /* Make sure the locking sequence is correct.
- ** (1) We never move from unlocked to anything higher than shared lock.
- ** (2) SQLite never explicitly requests a pendig lock.
- ** (3) A shared lock is always held when a reserve lock is requested.
- */
- assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
- assert( eFileLock!=PENDING_LOCK );
- assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
-
- /* This mutex is needed because pFile->pInode is shared across threads
- */
- pInode = pFile->pInode;
- sqlite3_mutex_enter(pInode->pLockMutex);
-
- /* If some thread using this PID has a lock via a different unixFile*
- ** handle that precludes the requested lock, return BUSY.
- */
- if( (pFile->eFileLock!=pInode->eFileLock &&
- (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
- ){
- rc = SQLITE_BUSY;
- goto end_lock;
- }
-
- /* If a SHARED lock is requested, and some thread using this PID already
- ** has a SHARED or RESERVED lock, then increment reference counts and
- ** return SQLITE_OK.
- */
- if( eFileLock==SHARED_LOCK &&
- (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
- assert( eFileLock==SHARED_LOCK );
- assert( pFile->eFileLock==0 );
- assert( pInode->nShared>0 );
- pFile->eFileLock = SHARED_LOCK;
- pInode->nShared++;
- pInode->nLock++;
- goto end_lock;
- }
-
-
- /* A PENDING lock is needed before acquiring a SHARED lock and before
- ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
- ** be released.
- */
- lock.l_len = 1L;
- lock.l_whence = SEEK_SET;
- if( eFileLock==SHARED_LOCK
- || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLocknShared==0 );
- assert( pInode->eFileLock==0 );
- assert( rc==SQLITE_OK );
-
- /* Now get the read-lock */
- lock.l_start = SHARED_FIRST;
- lock.l_len = SHARED_SIZE;
- if( unixFileLock(pFile, &lock) ){
- tErrno = errno;
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
- }
-
- /* Drop the temporary PENDING lock */
- lock.l_start = PENDING_BYTE;
- lock.l_len = 1L;
- lock.l_type = F_UNLCK;
- if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
- /* This could happen with a network mount */
- tErrno = errno;
- rc = SQLITE_IOERR_UNLOCK;
- }
-
- if( rc ){
- if( rc!=SQLITE_BUSY ){
- storeLastErrno(pFile, tErrno);
- }
- goto end_lock;
- }else{
- pFile->eFileLock = SHARED_LOCK;
- pInode->nLock++;
- pInode->nShared = 1;
- }
- }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
- /* We are trying for an exclusive lock but another thread in this
- ** same process is still holding a shared lock. */
- rc = SQLITE_BUSY;
- }else{
- /* The request was for a RESERVED or EXCLUSIVE lock. It is
- ** assumed that there is a SHARED or greater lock on the file
- ** already.
- */
- assert( 0!=pFile->eFileLock );
- lock.l_type = F_WRLCK;
-
- assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
- if( eFileLock==RESERVED_LOCK ){
- lock.l_start = RESERVED_BYTE;
- lock.l_len = 1L;
- }else{
- lock.l_start = SHARED_FIRST;
- lock.l_len = SHARED_SIZE;
- }
-
- if( unixFileLock(pFile, &lock) ){
- tErrno = errno;
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
- if( rc!=SQLITE_BUSY ){
- storeLastErrno(pFile, tErrno);
- }
- }
- }
-
-
-#ifdef SQLITE_DEBUG
- /* Set up the transaction-counter change checking flags when
- ** transitioning from a SHARED to a RESERVED lock. The change
- ** from SHARED to RESERVED marks the beginning of a normal
- ** write operation (not a hot journal rollback).
- */
- if( rc==SQLITE_OK
- && pFile->eFileLock<=SHARED_LOCK
- && eFileLock==RESERVED_LOCK
- ){
- pFile->transCntrChng = 0;
- pFile->dbUpdate = 0;
- pFile->inNormalWrite = 1;
- }
-#endif
-
-
- if( rc==SQLITE_OK ){
- pFile->eFileLock = eFileLock;
- pInode->eFileLock = eFileLock;
- }else if( eFileLock==EXCLUSIVE_LOCK ){
- pFile->eFileLock = PENDING_LOCK;
- pInode->eFileLock = PENDING_LOCK;
- }
-
-end_lock:
- sqlite3_mutex_leave(pInode->pLockMutex);
- OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
- rc==SQLITE_OK ? "ok" : "failed"));
- return rc;
-}
-
-/*
-** Add the file descriptor used by file handle pFile to the corresponding
-** pUnused list.
-*/
-static void setPendingFd(unixFile *pFile){
- unixInodeInfo *pInode = pFile->pInode;
- UnixUnusedFd *p = pFile->pPreallocatedUnused;
- assert( unixFileMutexHeld(pFile) );
- p->pNext = pInode->pUnused;
- pInode->pUnused = p;
- pFile->h = -1;
- pFile->pPreallocatedUnused = 0;
-}
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-**
-** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
-** the byte range is divided into 2 parts and the first part is unlocked then
-** set to a read lock, then the other part is simply unlocked. This works
-** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
-** remove the write lock on a region when a read lock is set.
-*/
-static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
- unixFile *pFile = (unixFile*)id;
- unixInodeInfo *pInode;
- struct flock lock;
- int rc = SQLITE_OK;
-
- assert( pFile );
- OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
- pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
- osGetpid(0)));
-
- assert( eFileLock<=SHARED_LOCK );
- if( pFile->eFileLock<=eFileLock ){
- return SQLITE_OK;
- }
- pInode = pFile->pInode;
- sqlite3_mutex_enter(pInode->pLockMutex);
- assert( pInode->nShared!=0 );
- if( pFile->eFileLock>SHARED_LOCK ){
- assert( pInode->eFileLock==pFile->eFileLock );
-
-#ifdef SQLITE_DEBUG
- /* When reducing a lock such that other processes can start
- ** reading the database file again, make sure that the
- ** transaction counter was updated if any part of the database
- ** file changed. If the transaction counter is not updated,
- ** other connections to the same file might not realize that
- ** the file has changed and hence might not know to flush their
- ** cache. The use of a stale cache can lead to database corruption.
- */
- pFile->inNormalWrite = 0;
-#endif
-
- /* downgrading to a shared lock on NFS involves clearing the write lock
- ** before establishing the readlock - to avoid a race condition we downgrade
- ** the lock in 2 blocks, so that part of the range will be covered by a
- ** write lock until the rest is covered by a read lock:
- ** 1: [WWWWW]
- ** 2: [....W]
- ** 3: [RRRRW]
- ** 4: [RRRR.]
- */
- if( eFileLock==SHARED_LOCK ){
-#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
- (void)handleNFSUnlock;
- assert( handleNFSUnlock==0 );
-#endif
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
- if( handleNFSUnlock ){
- int tErrno; /* Error code from system call errors */
- off_t divSize = SHARED_SIZE - 1;
-
- lock.l_type = F_UNLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = SHARED_FIRST;
- lock.l_len = divSize;
- if( unixFileLock(pFile, &lock)==(-1) ){
- tErrno = errno;
- rc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, tErrno);
- goto end_unlock;
- }
- lock.l_type = F_RDLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = SHARED_FIRST;
- lock.l_len = divSize;
- if( unixFileLock(pFile, &lock)==(-1) ){
- tErrno = errno;
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
- if( IS_LOCK_ERROR(rc) ){
- storeLastErrno(pFile, tErrno);
- }
- goto end_unlock;
- }
- lock.l_type = F_UNLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = SHARED_FIRST+divSize;
- lock.l_len = SHARED_SIZE-divSize;
- if( unixFileLock(pFile, &lock)==(-1) ){
- tErrno = errno;
- rc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, tErrno);
- goto end_unlock;
- }
- }else
-#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
- {
- lock.l_type = F_RDLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = SHARED_FIRST;
- lock.l_len = SHARED_SIZE;
- if( unixFileLock(pFile, &lock) ){
- /* In theory, the call to unixFileLock() cannot fail because another
- ** process is holding an incompatible lock. If it does, this
- ** indicates that the other process is not following the locking
- ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
- ** SQLITE_BUSY would confuse the upper layer (in practice it causes
- ** an assert to fail). */
- rc = SQLITE_IOERR_RDLOCK;
- storeLastErrno(pFile, errno);
- goto end_unlock;
- }
- }
- }
- lock.l_type = F_UNLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = PENDING_BYTE;
- lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
- if( unixFileLock(pFile, &lock)==0 ){
- pInode->eFileLock = SHARED_LOCK;
- }else{
- rc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, errno);
- goto end_unlock;
- }
- }
- if( eFileLock==NO_LOCK ){
- /* Decrement the shared lock counter. Release the lock using an
- ** OS call only when all threads in this same process have released
- ** the lock.
- */
- pInode->nShared--;
- if( pInode->nShared==0 ){
- lock.l_type = F_UNLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = lock.l_len = 0L;
- if( unixFileLock(pFile, &lock)==0 ){
- pInode->eFileLock = NO_LOCK;
- }else{
- rc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, errno);
- pInode->eFileLock = NO_LOCK;
- pFile->eFileLock = NO_LOCK;
- }
- }
-
- /* Decrement the count of locks against this same file. When the
- ** count reaches zero, close any other file descriptors whose close
- ** was deferred because of outstanding locks.
- */
- pInode->nLock--;
- assert( pInode->nLock>=0 );
- if( pInode->nLock==0 ) closePendingFds(pFile);
- }
-
-end_unlock:
- sqlite3_mutex_leave(pInode->pLockMutex);
- if( rc==SQLITE_OK ){
- pFile->eFileLock = eFileLock;
- }
- return rc;
-}
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-*/
-static int unixUnlock(sqlite3_file *id, int eFileLock){
-#if SQLITE_MAX_MMAP_SIZE>0
- assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
-#endif
- return posixUnlock(id, eFileLock, 0);
-}
-
-#if SQLITE_MAX_MMAP_SIZE>0
-static int unixMapfile(unixFile *pFd, i64 nByte);
-static void unixUnmapfile(unixFile *pFd);
-#endif
-
-/*
-** This function performs the parts of the "close file" operation
-** common to all locking schemes. It closes the directory and file
-** handles, if they are valid, and sets all fields of the unixFile
-** structure to 0.
-**
-** It is *not* necessary to hold the mutex when this routine is called,
-** even on VxWorks. A mutex will be acquired on VxWorks by the
-** vxworksReleaseFileId() routine.
-*/
-static int closeUnixFile(sqlite3_file *id){
- unixFile *pFile = (unixFile*)id;
-#if SQLITE_MAX_MMAP_SIZE>0
- unixUnmapfile(pFile);
-#endif
- if( pFile->h>=0 ){
- robust_close(pFile, pFile->h, __LINE__);
- pFile->h = -1;
- }
-#if OS_VXWORKS
- if( pFile->pId ){
- if( pFile->ctrlFlags & UNIXFILE_DELETE ){
- osUnlink(pFile->pId->zCanonicalName);
- }
- vxworksReleaseFileId(pFile->pId);
- pFile->pId = 0;
- }
-#endif
-#ifdef SQLITE_UNLINK_AFTER_CLOSE
- if( pFile->ctrlFlags & UNIXFILE_DELETE ){
- osUnlink(pFile->zPath);
- sqlite3_free(*(char**)&pFile->zPath);
- pFile->zPath = 0;
- }
-#endif
- OSTRACE(("CLOSE %-3d\n", pFile->h));
- OpenCounter(-1);
- sqlite3_free(pFile->pPreallocatedUnused);
- memset(pFile, 0, sizeof(unixFile));
- return SQLITE_OK;
-}
-
-/*
-** Close a file.
-*/
-static int unixClose(sqlite3_file *id){
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile *)id;
- unixInodeInfo *pInode = pFile->pInode;
-
- assert( pInode!=0 );
- verifyDbFile(pFile);
- unixUnlock(id, NO_LOCK);
- assert( unixFileMutexNotheld(pFile) );
- unixEnterMutex();
-
- /* unixFile.pInode is always valid here. Otherwise, a different close
- ** routine (e.g. nolockClose()) would be called instead.
- */
- assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
- sqlite3_mutex_enter(pInode->pLockMutex);
- if( pInode->nLock ){
- /* If there are outstanding locks, do not actually close the file just
- ** yet because that would clear those locks. Instead, add the file
- ** descriptor to pInode->pUnused list. It will be automatically closed
- ** when the last lock is cleared.
- */
- setPendingFd(pFile);
- }
- sqlite3_mutex_leave(pInode->pLockMutex);
- releaseInodeInfo(pFile);
- rc = closeUnixFile(id);
- unixLeaveMutex();
- return rc;
-}
-
-/************** End of the posix advisory lock implementation *****************
-******************************************************************************/
-
-/******************************************************************************
-****************************** No-op Locking **********************************
-**
-** Of the various locking implementations available, this is by far the
-** simplest: locking is ignored. No attempt is made to lock the database
-** file for reading or writing.
-**
-** This locking mode is appropriate for use on read-only databases
-** (ex: databases that are burned into CD-ROM, for example.) It can
-** also be used if the application employs some external mechanism to
-** prevent simultaneous access of the same database by two or more
-** database connections. But there is a serious risk of database
-** corruption if this locking mode is used in situations where multiple
-** database connections are accessing the same database file at the same
-** time and one or more of those connections are writing.
-*/
-
-static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
- UNUSED_PARAMETER(NotUsed);
- *pResOut = 0;
- return SQLITE_OK;
-}
-static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
- UNUSED_PARAMETER2(NotUsed, NotUsed2);
- return SQLITE_OK;
-}
-static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
- UNUSED_PARAMETER2(NotUsed, NotUsed2);
- return SQLITE_OK;
-}
-
-/*
-** Close the file.
-*/
-static int nolockClose(sqlite3_file *id) {
- return closeUnixFile(id);
-}
-
-/******************* End of the no-op lock implementation *********************
-******************************************************************************/
-
-/******************************************************************************
-************************* Begin dot-file Locking ******************************
-**
-** The dotfile locking implementation uses the existence of separate lock
-** files (really a directory) to control access to the database. This works
-** on just about every filesystem imaginable. But there are serious downsides:
-**
-** (1) There is zero concurrency. A single reader blocks all other
-** connections from reading or writing the database.
-**
-** (2) An application crash or power loss can leave stale lock files
-** sitting around that need to be cleared manually.
-**
-** Nevertheless, a dotlock is an appropriate locking mode for use if no
-** other locking strategy is available.
-**
-** Dotfile locking works by creating a subdirectory in the same directory as
-** the database and with the same name but with a ".lock" extension added.
-** The existence of a lock directory implies an EXCLUSIVE lock. All other
-** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
-*/
-
-/*
-** The file suffix added to the data base filename in order to create the
-** lock directory.
-*/
-#define DOTLOCK_SUFFIX ".lock"
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-**
-** In dotfile locking, either a lock exists or it does not. So in this
-** variation of CheckReservedLock(), *pResOut is set to true if any lock
-** is held on the file and false if the file is unlocked.
-*/
-static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
- int rc = SQLITE_OK;
- int reserved = 0;
- unixFile *pFile = (unixFile*)id;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-
- assert( pFile );
- reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
- OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
- *pResOut = reserved;
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-**
-** With dotfile locking, we really only support state (4): EXCLUSIVE.
-** But we track the other locking levels internally.
-*/
-static int dotlockLock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- char *zLockFile = (char *)pFile->lockingContext;
- int rc = SQLITE_OK;
-
-
- /* If we have any lock, then the lock file already exists. All we have
- ** to do is adjust our internal record of the lock level.
- */
- if( pFile->eFileLock > NO_LOCK ){
- pFile->eFileLock = eFileLock;
- /* Always update the timestamp on the old file */
-#ifdef HAVE_UTIME
- utime(zLockFile, NULL);
-#else
- utimes(zLockFile, NULL);
-#endif
- return SQLITE_OK;
- }
-
- /* grab an exclusive lock */
- rc = osMkdir(zLockFile, 0777);
- if( rc<0 ){
- /* failed to open/create the lock directory */
- int tErrno = errno;
- if( EEXIST == tErrno ){
- rc = SQLITE_BUSY;
- } else {
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
- if( rc!=SQLITE_BUSY ){
- storeLastErrno(pFile, tErrno);
- }
- }
- return rc;
- }
-
- /* got it, set the type and return ok */
- pFile->eFileLock = eFileLock;
- return rc;
-}
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-**
-** When the locking level reaches NO_LOCK, delete the lock file.
-*/
-static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- char *zLockFile = (char *)pFile->lockingContext;
- int rc;
-
- assert( pFile );
- OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
- pFile->eFileLock, osGetpid(0)));
- assert( eFileLock<=SHARED_LOCK );
-
- /* no-op if possible */
- if( pFile->eFileLock==eFileLock ){
- return SQLITE_OK;
- }
-
- /* To downgrade to shared, simply update our internal notion of the
- ** lock state. No need to mess with the file on disk.
- */
- if( eFileLock==SHARED_LOCK ){
- pFile->eFileLock = SHARED_LOCK;
- return SQLITE_OK;
- }
-
- /* To fully unlock the database, delete the lock file */
- assert( eFileLock==NO_LOCK );
- rc = osRmdir(zLockFile);
- if( rc<0 ){
- int tErrno = errno;
- if( tErrno==ENOENT ){
- rc = SQLITE_OK;
- }else{
- rc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, tErrno);
- }
- return rc;
- }
- pFile->eFileLock = NO_LOCK;
- return SQLITE_OK;
-}
-
-/*
-** Close a file. Make sure the lock has been released before closing.
-*/
-static int dotlockClose(sqlite3_file *id) {
- unixFile *pFile = (unixFile*)id;
- assert( id!=0 );
- dotlockUnlock(id, NO_LOCK);
- sqlite3_free(pFile->lockingContext);
- return closeUnixFile(id);
-}
-/****************** End of the dot-file lock implementation *******************
-******************************************************************************/
-
-/******************************************************************************
-************************** Begin flock Locking ********************************
-**
-** Use the flock() system call to do file locking.
-**
-** flock() locking is like dot-file locking in that the various
-** fine-grain locking levels supported by SQLite are collapsed into
-** a single exclusive lock. In other words, SHARED, RESERVED, and
-** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
-** still works when you do this, but concurrency is reduced since
-** only a single process can be reading the database at a time.
-**
-** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
-*/
-#if SQLITE_ENABLE_LOCKING_STYLE
-
-/*
-** Retry flock() calls that fail with EINTR
-*/
-#ifdef EINTR
-static int robust_flock(int fd, int op){
- int rc;
- do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
- return rc;
-}
-#else
-# define robust_flock(a,b) flock(a,b)
-#endif
-
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-*/
-static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
- int rc = SQLITE_OK;
- int reserved = 0;
- unixFile *pFile = (unixFile*)id;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-
- assert( pFile );
-
- /* Check if a thread in this process holds such a lock */
- if( pFile->eFileLock>SHARED_LOCK ){
- reserved = 1;
- }
-
- /* Otherwise see if some other process holds it. */
- if( !reserved ){
- /* attempt to get the lock */
- int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
- if( !lrc ){
- /* got the lock, unlock it */
- lrc = robust_flock(pFile->h, LOCK_UN);
- if ( lrc ) {
- int tErrno = errno;
- /* unlock failed with an error */
- lrc = SQLITE_IOERR_UNLOCK;
- storeLastErrno(pFile, tErrno);
- rc = lrc;
- }
- } else {
- int tErrno = errno;
- reserved = 1;
- /* someone else might have it reserved */
- lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
- if( IS_LOCK_ERROR(lrc) ){
- storeLastErrno(pFile, tErrno);
- rc = lrc;
- }
- }
- }
- OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
-
-#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
- if( (rc & 0xff) == SQLITE_IOERR ){
- rc = SQLITE_OK;
- reserved=1;
- }
-#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
- *pResOut = reserved;
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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
-**
-** flock() only really support EXCLUSIVE locks. We track intermediate
-** lock states in the sqlite3_file structure, but all locks SHARED or
-** above are really EXCLUSIVE locks and exclude all other processes from
-** access the file.
-**
-** This routine will only increase a lock. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-*/
-static int flockLock(sqlite3_file *id, int eFileLock) {
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile*)id;
-
- assert( pFile );
-
- /* if we already have a lock, it is exclusive.
- ** Just adjust level and punt on outta here. */
- if (pFile->eFileLock > NO_LOCK) {
- pFile->eFileLock = eFileLock;
- return SQLITE_OK;
- }
-
- /* grab an exclusive lock */
-
- if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
- int tErrno = errno;
- /* didn't get, must be busy */
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
- if( IS_LOCK_ERROR(rc) ){
- storeLastErrno(pFile, tErrno);
- }
- } else {
- /* got it, set the type and return ok */
- pFile->eFileLock = eFileLock;
- }
- OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
- rc==SQLITE_OK ? "ok" : "failed"));
-#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
- if( (rc & 0xff) == SQLITE_IOERR ){
- rc = SQLITE_BUSY;
- }
-#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
- return rc;
-}
-
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-*/
-static int flockUnlock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
-
- assert( pFile );
- OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
- pFile->eFileLock, osGetpid(0)));
- assert( eFileLock<=SHARED_LOCK );
-
- /* no-op if possible */
- if( pFile->eFileLock==eFileLock ){
- return SQLITE_OK;
- }
-
- /* shared can just be set because we always have an exclusive */
- if (eFileLock==SHARED_LOCK) {
- pFile->eFileLock = eFileLock;
- return SQLITE_OK;
- }
-
- /* no, really, unlock. */
- if( robust_flock(pFile->h, LOCK_UN) ){
-#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
- return SQLITE_OK;
-#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
- return SQLITE_IOERR_UNLOCK;
- }else{
- pFile->eFileLock = NO_LOCK;
- return SQLITE_OK;
- }
-}
-
-/*
-** Close a file.
-*/
-static int flockClose(sqlite3_file *id) {
- assert( id!=0 );
- flockUnlock(id, NO_LOCK);
- return closeUnixFile(id);
-}
-
-#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
-
-/******************* End of the flock lock implementation *********************
-******************************************************************************/
-
-/******************************************************************************
-************************ Begin Named Semaphore Locking ************************
-**
-** Named semaphore locking is only supported on VxWorks.
-**
-** Semaphore locking is like dot-lock and flock in that it really only
-** supports EXCLUSIVE locking. Only a single process can read or write
-** the database file at a time. This reduces potential concurrency, but
-** makes the lock implementation much easier.
-*/
-#if OS_VXWORKS
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-*/
-static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
- int rc = SQLITE_OK;
- int reserved = 0;
- unixFile *pFile = (unixFile*)id;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-
- assert( pFile );
-
- /* Check if a thread in this process holds such a lock */
- if( pFile->eFileLock>SHARED_LOCK ){
- reserved = 1;
- }
-
- /* Otherwise see if some other process holds it. */
- if( !reserved ){
- sem_t *pSem = pFile->pInode->pSem;
-
- if( sem_trywait(pSem)==-1 ){
- int tErrno = errno;
- if( EAGAIN != tErrno ){
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
- storeLastErrno(pFile, tErrno);
- } else {
- /* someone else has the lock when we are in NO_LOCK */
- reserved = (pFile->eFileLock < SHARED_LOCK);
- }
- }else{
- /* we could have it if we want it */
- sem_post(pSem);
- }
- }
- OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
-
- *pResOut = reserved;
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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
-**
-** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
-** lock states in the sqlite3_file structure, but all locks SHARED or
-** above are really EXCLUSIVE locks and exclude all other processes from
-** access the file.
-**
-** This routine will only increase a lock. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-*/
-static int semXLock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- sem_t *pSem = pFile->pInode->pSem;
- int rc = SQLITE_OK;
-
- /* if we already have a lock, it is exclusive.
- ** Just adjust level and punt on outta here. */
- if (pFile->eFileLock > NO_LOCK) {
- pFile->eFileLock = eFileLock;
- rc = SQLITE_OK;
- goto sem_end_lock;
- }
-
- /* lock semaphore now but bail out when already locked. */
- if( sem_trywait(pSem)==-1 ){
- rc = SQLITE_BUSY;
- goto sem_end_lock;
- }
-
- /* got it, set the type and return ok */
- pFile->eFileLock = eFileLock;
-
- sem_end_lock:
- return rc;
-}
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-*/
-static int semXUnlock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- sem_t *pSem = pFile->pInode->pSem;
-
- assert( pFile );
- assert( pSem );
- OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
- pFile->eFileLock, osGetpid(0)));
- assert( eFileLock<=SHARED_LOCK );
-
- /* no-op if possible */
- if( pFile->eFileLock==eFileLock ){
- return SQLITE_OK;
- }
-
- /* shared can just be set because we always have an exclusive */
- if (eFileLock==SHARED_LOCK) {
- pFile->eFileLock = eFileLock;
- return SQLITE_OK;
- }
-
- /* no, really unlock. */
- if ( sem_post(pSem)==-1 ) {
- int rc, tErrno = errno;
- rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
- if( IS_LOCK_ERROR(rc) ){
- storeLastErrno(pFile, tErrno);
- }
- return rc;
- }
- pFile->eFileLock = NO_LOCK;
- return SQLITE_OK;
-}
-
-/*
- ** Close a file.
- */
-static int semXClose(sqlite3_file *id) {
- if( id ){
- unixFile *pFile = (unixFile*)id;
- semXUnlock(id, NO_LOCK);
- assert( pFile );
- assert( unixFileMutexNotheld(pFile) );
- unixEnterMutex();
- releaseInodeInfo(pFile);
- unixLeaveMutex();
- closeUnixFile(id);
- }
- return SQLITE_OK;
-}
-
-#endif /* OS_VXWORKS */
-/*
-** Named semaphore locking is only available on VxWorks.
-**
-*************** End of the named semaphore lock implementation ****************
-******************************************************************************/
-
-
-/******************************************************************************
-*************************** Begin AFP Locking *********************************
-**
-** AFP is the Apple Filing Protocol. AFP is a network filesystem found
-** on Apple Macintosh computers - both OS9 and OSX.
-**
-** Third-party implementations of AFP are available. But this code here
-** only works on OSX.
-*/
-
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-/*
-** The afpLockingContext structure contains all afp lock specific state
-*/
-typedef struct afpLockingContext afpLockingContext;
-struct afpLockingContext {
- int reserved;
- const char *dbPath; /* Name of the open file */
-};
-
-struct ByteRangeLockPB2
-{
- unsigned long long offset; /* offset to first byte to lock */
- unsigned long long length; /* nbr of bytes to lock */
- unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
- unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
- unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
- int fd; /* file desc to assoc this lock with */
-};
-
-#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
-
-/*
-** This is a utility for setting or clearing a bit-range lock on an
-** AFP filesystem.
-**
-** Return SQLITE_OK on success, SQLITE_BUSY on failure.
-*/
-static int afpSetLock(
- const char *path, /* Name of the file to be locked or unlocked */
- unixFile *pFile, /* Open file descriptor on path */
- unsigned long long offset, /* First byte to be locked */
- unsigned long long length, /* Number of bytes to lock */
- int setLockFlag /* True to set lock. False to clear lock */
-){
- struct ByteRangeLockPB2 pb;
- int err;
-
- pb.unLockFlag = setLockFlag ? 0 : 1;
- pb.startEndFlag = 0;
- pb.offset = offset;
- pb.length = length;
- pb.fd = pFile->h;
-
- OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
- (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
- offset, length));
- err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
- if ( err==-1 ) {
- int rc;
- int tErrno = errno;
- OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
- path, tErrno, strerror(tErrno)));
-#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
- rc = SQLITE_BUSY;
-#else
- rc = sqliteErrorFromPosixError(tErrno,
- setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
-#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
- if( IS_LOCK_ERROR(rc) ){
- storeLastErrno(pFile, tErrno);
- }
- return rc;
- } else {
- return SQLITE_OK;
- }
-}
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-*/
-static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
- int rc = SQLITE_OK;
- int reserved = 0;
- unixFile *pFile = (unixFile*)id;
- afpLockingContext *context;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-
- assert( pFile );
- context = (afpLockingContext *) pFile->lockingContext;
- if( context->reserved ){
- *pResOut = 1;
- return SQLITE_OK;
- }
- sqlite3_mutex_enter(pFile->pInode->pLockMutex);
- /* Check if a thread in this process holds such a lock */
- if( pFile->pInode->eFileLock>SHARED_LOCK ){
- reserved = 1;
- }
-
- /* Otherwise see if some other process holds it.
- */
- if( !reserved ){
- /* lock the RESERVED byte */
- int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
- if( SQLITE_OK==lrc ){
- /* if we succeeded in taking the reserved lock, unlock it to restore
- ** the original state */
- lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
- } else {
- /* if we failed to get the lock then someone else must have it */
- reserved = 1;
- }
- if( IS_LOCK_ERROR(lrc) ){
- rc=lrc;
- }
- }
-
- sqlite3_mutex_leave(pFile->pInode->pLockMutex);
- OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
-
- *pResOut = reserved;
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-*/
-static int afpLock(sqlite3_file *id, int eFileLock){
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile*)id;
- unixInodeInfo *pInode = pFile->pInode;
- afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
-
- assert( pFile );
- OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
- azFileLock(eFileLock), azFileLock(pFile->eFileLock),
- azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
-
- /* If there is already a lock of this type or more restrictive on the
- ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
- ** unixEnterMutex() hasn't been called yet.
- */
- if( pFile->eFileLock>=eFileLock ){
- OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
- azFileLock(eFileLock)));
- return SQLITE_OK;
- }
-
- /* Make sure the locking sequence is correct
- ** (1) We never move from unlocked to anything higher than shared lock.
- ** (2) SQLite never explicitly requests a pendig lock.
- ** (3) A shared lock is always held when a reserve lock is requested.
- */
- assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
- assert( eFileLock!=PENDING_LOCK );
- assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
-
- /* This mutex is needed because pFile->pInode is shared across threads
- */
- pInode = pFile->pInode;
- sqlite3_mutex_enter(pInode->pLockMutex);
-
- /* If some thread using this PID has a lock via a different unixFile*
- ** handle that precludes the requested lock, return BUSY.
- */
- if( (pFile->eFileLock!=pInode->eFileLock &&
- (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
- ){
- rc = SQLITE_BUSY;
- goto afp_end_lock;
- }
-
- /* If a SHARED lock is requested, and some thread using this PID already
- ** has a SHARED or RESERVED lock, then increment reference counts and
- ** return SQLITE_OK.
- */
- if( eFileLock==SHARED_LOCK &&
- (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
- assert( eFileLock==SHARED_LOCK );
- assert( pFile->eFileLock==0 );
- assert( pInode->nShared>0 );
- pFile->eFileLock = SHARED_LOCK;
- pInode->nShared++;
- pInode->nLock++;
- goto afp_end_lock;
- }
-
- /* A PENDING lock is needed before acquiring a SHARED lock and before
- ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
- ** be released.
- */
- if( eFileLock==SHARED_LOCK
- || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLockdbPath, pFile, PENDING_BYTE, 1, 1);
- if (failed) {
- rc = failed;
- goto afp_end_lock;
- }
- }
-
- /* If control gets to this point, then actually go ahead and make
- ** operating system calls for the specified lock.
- */
- if( eFileLock==SHARED_LOCK ){
- int lrc1, lrc2, lrc1Errno = 0;
- long lk, mask;
-
- assert( pInode->nShared==0 );
- assert( pInode->eFileLock==0 );
-
- mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
- /* Now get the read-lock SHARED_LOCK */
- /* note that the quality of the randomness doesn't matter that much */
- lk = random();
- pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
- lrc1 = afpSetLock(context->dbPath, pFile,
- SHARED_FIRST+pInode->sharedByte, 1, 1);
- if( IS_LOCK_ERROR(lrc1) ){
- lrc1Errno = pFile->lastErrno;
- }
- /* Drop the temporary PENDING lock */
- lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
-
- if( IS_LOCK_ERROR(lrc1) ) {
- storeLastErrno(pFile, lrc1Errno);
- rc = lrc1;
- goto afp_end_lock;
- } else if( IS_LOCK_ERROR(lrc2) ){
- rc = lrc2;
- goto afp_end_lock;
- } else if( lrc1 != SQLITE_OK ) {
- rc = lrc1;
- } else {
- pFile->eFileLock = SHARED_LOCK;
- pInode->nLock++;
- pInode->nShared = 1;
- }
- }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
- /* We are trying for an exclusive lock but another thread in this
- ** same process is still holding a shared lock. */
- rc = SQLITE_BUSY;
- }else{
- /* The request was for a RESERVED or EXCLUSIVE lock. It is
- ** assumed that there is a SHARED or greater lock on the file
- ** already.
- */
- int failed = 0;
- assert( 0!=pFile->eFileLock );
- if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
- /* Acquire a RESERVED lock */
- failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
- if( !failed ){
- context->reserved = 1;
- }
- }
- if (!failed && eFileLock == EXCLUSIVE_LOCK) {
- /* Acquire an EXCLUSIVE lock */
-
- /* Remove the shared lock before trying the range. we'll need to
- ** reestablish the shared lock if we can't get the afpUnlock
- */
- if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
- pInode->sharedByte, 1, 0)) ){
- int failed2 = SQLITE_OK;
- /* now attemmpt to get the exclusive lock range */
- failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
- SHARED_SIZE, 1);
- if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
- SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
- /* Can't reestablish the shared lock. Sqlite can't deal, this is
- ** a critical I/O error
- */
- rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
- SQLITE_IOERR_LOCK;
- goto afp_end_lock;
- }
- }else{
- rc = failed;
- }
- }
- if( failed ){
- rc = failed;
- }
- }
-
- if( rc==SQLITE_OK ){
- pFile->eFileLock = eFileLock;
- pInode->eFileLock = eFileLock;
- }else if( eFileLock==EXCLUSIVE_LOCK ){
- pFile->eFileLock = PENDING_LOCK;
- pInode->eFileLock = PENDING_LOCK;
- }
-
-afp_end_lock:
- sqlite3_mutex_leave(pInode->pLockMutex);
- OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
- rc==SQLITE_OK ? "ok" : "failed"));
- return rc;
-}
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-*/
-static int afpUnlock(sqlite3_file *id, int eFileLock) {
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile*)id;
- unixInodeInfo *pInode;
- afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
- int skipShared = 0;
-#ifdef SQLITE_TEST
- int h = pFile->h;
-#endif
-
- assert( pFile );
- OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
- pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
- osGetpid(0)));
-
- assert( eFileLock<=SHARED_LOCK );
- if( pFile->eFileLock<=eFileLock ){
- return SQLITE_OK;
- }
- pInode = pFile->pInode;
- sqlite3_mutex_enter(pInode->pLockMutex);
- assert( pInode->nShared!=0 );
- if( pFile->eFileLock>SHARED_LOCK ){
- assert( pInode->eFileLock==pFile->eFileLock );
- SimulateIOErrorBenign(1);
- SimulateIOError( h=(-1) )
- SimulateIOErrorBenign(0);
-
-#ifdef SQLITE_DEBUG
- /* When reducing a lock such that other processes can start
- ** reading the database file again, make sure that the
- ** transaction counter was updated if any part of the database
- ** file changed. If the transaction counter is not updated,
- ** other connections to the same file might not realize that
- ** the file has changed and hence might not know to flush their
- ** cache. The use of a stale cache can lead to database corruption.
- */
- assert( pFile->inNormalWrite==0
- || pFile->dbUpdate==0
- || pFile->transCntrChng==1 );
- pFile->inNormalWrite = 0;
-#endif
-
- if( pFile->eFileLock==EXCLUSIVE_LOCK ){
- rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
- if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
- /* only re-establish the shared lock if necessary */
- int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
- rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
- } else {
- skipShared = 1;
- }
- }
- if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
- rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
- }
- if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
- rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
- if( !rc ){
- context->reserved = 0;
- }
- }
- if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
- pInode->eFileLock = SHARED_LOCK;
- }
- }
- if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
-
- /* Decrement the shared lock counter. Release the lock using an
- ** OS call only when all threads in this same process have released
- ** the lock.
- */
- unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
- pInode->nShared--;
- if( pInode->nShared==0 ){
- SimulateIOErrorBenign(1);
- SimulateIOError( h=(-1) )
- SimulateIOErrorBenign(0);
- if( !skipShared ){
- rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
- }
- if( !rc ){
- pInode->eFileLock = NO_LOCK;
- pFile->eFileLock = NO_LOCK;
- }
- }
- if( rc==SQLITE_OK ){
- pInode->nLock--;
- assert( pInode->nLock>=0 );
- if( pInode->nLock==0 ) closePendingFds(pFile);
- }
- }
-
- sqlite3_mutex_leave(pInode->pLockMutex);
- if( rc==SQLITE_OK ){
- pFile->eFileLock = eFileLock;
- }
- return rc;
-}
-
-/*
-** Close a file & cleanup AFP specific locking context
-*/
-static int afpClose(sqlite3_file *id) {
- int rc = SQLITE_OK;
- unixFile *pFile = (unixFile*)id;
- assert( id!=0 );
- afpUnlock(id, NO_LOCK);
- assert( unixFileMutexNotheld(pFile) );
- unixEnterMutex();
- if( pFile->pInode ){
- unixInodeInfo *pInode = pFile->pInode;
- sqlite3_mutex_enter(pInode->pLockMutex);
- if( pInode->nLock ){
- /* If there are outstanding locks, do not actually close the file just
- ** yet because that would clear those locks. Instead, add the file
- ** descriptor to pInode->aPending. It will be automatically closed when
- ** the last lock is cleared.
- */
- setPendingFd(pFile);
- }
- sqlite3_mutex_leave(pInode->pLockMutex);
- }
- releaseInodeInfo(pFile);
- sqlite3_free(pFile->lockingContext);
- rc = closeUnixFile(id);
- unixLeaveMutex();
- return rc;
-}
-
-#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
-/*
-** The code above is the AFP lock implementation. The code is specific
-** to MacOSX and does not work on other unix platforms. No alternative
-** is available. If you don't compile for a mac, then the "unix-afp"
-** VFS is not available.
-**
-********************* End of the AFP lock implementation **********************
-******************************************************************************/
-
-/******************************************************************************
-*************************** Begin NFS Locking ********************************/
-
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-/*
- ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
- ** 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.
- */
-static int nfsUnlock(sqlite3_file *id, int eFileLock){
- return posixUnlock(id, eFileLock, 1);
-}
-
-#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
-/*
-** The code above is the NFS lock implementation. The code is specific
-** to MacOSX and does not work on other unix platforms. No alternative
-** is available.
-**
-********************* End of the NFS lock implementation **********************
-******************************************************************************/
-
-/******************************************************************************
-**************** Non-locking sqlite3_file methods *****************************
-**
-** The next division contains implementations for all methods of the
-** sqlite3_file object other than the locking methods. The locking
-** methods were defined in divisions above (one locking method per
-** division). Those methods that are common to all locking modes
-** are gather together into this division.
-*/
-
-/*
-** Seek to the offset passed as the second argument, then read cnt
-** bytes into pBuf. Return the number of bytes actually read.
-**
-** NB: If you define USE_PREAD or USE_PREAD64, then it might also
-** be necessary to define _XOPEN_SOURCE to be 500. This varies from
-** one system to another. Since SQLite does not define USE_PREAD
-** in any form by default, we will not attempt to define _XOPEN_SOURCE.
-** See tickets #2741 and #2681.
-**
-** To avoid stomping the errno value on a failed read the lastErrno value
-** is set before returning.
-*/
-static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
- int got;
- int prior = 0;
-#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
- i64 newOffset;
-#endif
- TIMER_START;
- assert( cnt==(cnt&0x1ffff) );
- assert( id->h>2 );
- do{
-#if defined(USE_PREAD)
- got = osPread(id->h, pBuf, cnt, offset);
- SimulateIOError( got = -1 );
-#elif defined(USE_PREAD64)
- got = osPread64(id->h, pBuf, cnt, offset);
- SimulateIOError( got = -1 );
-#else
- newOffset = lseek(id->h, offset, SEEK_SET);
- SimulateIOError( newOffset = -1 );
- if( newOffset<0 ){
- storeLastErrno((unixFile*)id, errno);
- return -1;
- }
- got = osRead(id->h, pBuf, cnt);
-#endif
- if( got==cnt ) break;
- if( got<0 ){
- if( errno==EINTR ){ got = 1; continue; }
- prior = 0;
- storeLastErrno((unixFile*)id, errno);
- break;
- }else if( got>0 ){
- cnt -= got;
- offset += got;
- prior += got;
- pBuf = (void*)(got + (char*)pBuf);
- }
- }while( got>0 );
- TIMER_END;
- OSTRACE(("READ %-3d %5d %7lld %llu\n",
- id->h, got+prior, offset-prior, TIMER_ELAPSED));
- return got+prior;
-}
-
-/*
-** 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 unixRead(
- sqlite3_file *id,
- void *pBuf,
- int amt,
- sqlite3_int64 offset
-){
- unixFile *pFile = (unixFile *)id;
- int got;
- assert( id );
- assert( offset>=0 );
- assert( amt>0 );
-
- /* If this is a database file (not a journal, master-journal or temp
- ** file), the bytes in the locking range should never be read or written. */
-#if 0
- assert( pFile->pPreallocatedUnused==0
- || offset>=PENDING_BYTE+512
- || offset+amt<=PENDING_BYTE
- );
-#endif
-
-#if SQLITE_MAX_MMAP_SIZE>0
- /* Deal with as much of this read request as possible by transfering
- ** data from the memory mapping using memcpy(). */
- if( offsetmmapSize ){
- if( offset+amt <= pFile->mmapSize ){
- memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
- return SQLITE_OK;
- }else{
- int nCopy = pFile->mmapSize - offset;
- memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
- pBuf = &((u8 *)pBuf)[nCopy];
- amt -= nCopy;
- offset += nCopy;
- }
- }
-#endif
-
- got = seekAndRead(pFile, offset, pBuf, amt);
- if( got==amt ){
- return SQLITE_OK;
- }else if( got<0 ){
- /* lastErrno set by seekAndRead */
- return SQLITE_IOERR_READ;
- }else{
- storeLastErrno(pFile, 0); /* not a system error */
- /* Unread parts of the buffer must be zero-filled */
- memset(&((char*)pBuf)[got], 0, amt-got);
- return SQLITE_IOERR_SHORT_READ;
- }
-}
-
-/*
-** Attempt to seek the file-descriptor passed as the first argument to
-** absolute offset iOff, then attempt to write nBuf bytes of data from
-** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
-** return the actual number of bytes written (which may be less than
-** nBuf).
-*/
-static int seekAndWriteFd(
- int fd, /* File descriptor to write to */
- i64 iOff, /* File offset to begin writing at */
- const void *pBuf, /* Copy data from this buffer to the file */
- int nBuf, /* Size of buffer pBuf in bytes */
- int *piErrno /* OUT: Error number if error occurs */
-){
- int rc = 0; /* Value returned by system call */
-
- assert( nBuf==(nBuf&0x1ffff) );
- assert( fd>2 );
- assert( piErrno!=0 );
- nBuf &= 0x1ffff;
- TIMER_START;
-
-#if defined(USE_PREAD)
- do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
-#elif defined(USE_PREAD64)
- do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
-#else
- do{
- i64 iSeek = lseek(fd, iOff, SEEK_SET);
- SimulateIOError( iSeek = -1 );
- if( iSeek<0 ){
- rc = -1;
- break;
- }
- rc = osWrite(fd, pBuf, nBuf);
- }while( rc<0 && errno==EINTR );
-#endif
-
- TIMER_END;
- OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
-
- if( rc<0 ) *piErrno = errno;
- return rc;
-}
-
-
-/*
-** Seek to the offset in id->offset then read cnt bytes into pBuf.
-** Return the number of bytes actually read. Update the offset.
-**
-** To avoid stomping the errno value on a failed write the lastErrno value
-** is set before returning.
-*/
-static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
- return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
-}
-
-
-/*
-** Write data from a buffer into a file. Return SQLITE_OK on success
-** or some other error code on failure.
-*/
-static int unixWrite(
- sqlite3_file *id,
- const void *pBuf,
- int amt,
- sqlite3_int64 offset
-){
- unixFile *pFile = (unixFile*)id;
- int wrote = 0;
- assert( id );
- assert( amt>0 );
-
- /* If this is a database file (not a journal, master-journal or temp
- ** file), the bytes in the locking range should never be read or written. */
-#if 0
- assert( pFile->pPreallocatedUnused==0
- || offset>=PENDING_BYTE+512
- || offset+amt<=PENDING_BYTE
- );
-#endif
-
-#ifdef SQLITE_DEBUG
- /* If we are doing a normal write to a database file (as opposed to
- ** doing a hot-journal rollback or a write to some file other than a
- ** normal database file) then record the fact that the database
- ** has changed. If the transaction counter is modified, record that
- ** fact too.
- */
- if( pFile->inNormalWrite ){
- pFile->dbUpdate = 1; /* The database has been modified */
- if( offset<=24 && offset+amt>=27 ){
- int rc;
- char oldCntr[4];
- SimulateIOErrorBenign(1);
- rc = seekAndRead(pFile, 24, oldCntr, 4);
- SimulateIOErrorBenign(0);
- if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
- pFile->transCntrChng = 1; /* The transaction counter has changed */
- }
- }
- }
-#endif
-
-#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
- /* Deal with as much of this write request as possible by transfering
- ** data from the memory mapping using memcpy(). */
- if( offsetmmapSize ){
- if( offset+amt <= pFile->mmapSize ){
- memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
- return SQLITE_OK;
- }else{
- int nCopy = pFile->mmapSize - offset;
- memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
- pBuf = &((u8 *)pBuf)[nCopy];
- amt -= nCopy;
- offset += nCopy;
- }
- }
-#endif
-
- while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))0 ){
- amt -= wrote;
- offset += wrote;
- pBuf = &((char*)pBuf)[wrote];
- }
- SimulateIOError(( wrote=(-1), amt=1 ));
- SimulateDiskfullError(( wrote=0, amt=1 ));
-
- if( amt>wrote ){
- if( wrote<0 && pFile->lastErrno!=ENOSPC ){
- /* lastErrno set by seekAndWrite */
- return SQLITE_IOERR_WRITE;
- }else{
- storeLastErrno(pFile, 0); /* not a system error */
- return SQLITE_FULL;
- }
- }
-
- return SQLITE_OK;
-}
-
-#ifdef SQLITE_TEST
-/*
-** Count the number of fullsyncs and normal syncs. This is used to test
-** that syncs and fullsyncs are occurring at the right times.
-*/
-SQLITE_API int sqlite3_sync_count = 0;
-SQLITE_API int sqlite3_fullsync_count = 0;
-#endif
-
-/*
-** We do not trust systems to provide a working fdatasync(). Some do.
-** Others do no. To be safe, we will stick with the (slightly slower)
-** fsync(). If you know that your system does support fdatasync() correctly,
-** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
-*/
-#if !defined(fdatasync) && !HAVE_FDATASYNC
-# define fdatasync fsync
-#endif
-
-/*
-** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
-** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
-** only available on Mac OS X. But that could change.
-*/
-#ifdef F_FULLFSYNC
-# define HAVE_FULLFSYNC 1
-#else
-# define HAVE_FULLFSYNC 0
-#endif
-
-
-/*
-** The fsync() system call does not work as advertised on many
-** unix systems. The following procedure is an attempt to make
-** it work better.
-**
-** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
-** for testing when we want to run through the test suite quickly.
-** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
-** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
-** or power failure will likely corrupt the database file.
-**
-** SQLite sets the dataOnly flag if the size of the file is unchanged.
-** The idea behind dataOnly is that it should only write the file content
-** to disk, not the inode. We only set dataOnly if the file size is
-** unchanged since the file size is part of the inode. However,
-** Ted Ts'o tells us that fdatasync() will also write the inode if the
-** file size has changed. The only real difference between fdatasync()
-** and fsync(), Ted tells us, is that fdatasync() will not flush the
-** inode if the mtime or owner or other inode attributes have changed.
-** We only care about the file size, not the other file attributes, so
-** as far as SQLite is concerned, an fdatasync() is always adequate.
-** So, we always use fdatasync() if it is available, regardless of
-** the value of the dataOnly flag.
-*/
-static int full_fsync(int fd, int fullSync, int dataOnly){
- int rc;
-
- /* The following "ifdef/elif/else/" block has the same structure as
- ** the one below. It is replicated here solely to avoid cluttering
- ** up the real code with the UNUSED_PARAMETER() macros.
- */
-#ifdef SQLITE_NO_SYNC
- UNUSED_PARAMETER(fd);
- UNUSED_PARAMETER(fullSync);
- UNUSED_PARAMETER(dataOnly);
-#elif HAVE_FULLFSYNC
- UNUSED_PARAMETER(dataOnly);
-#else
- UNUSED_PARAMETER(fullSync);
- UNUSED_PARAMETER(dataOnly);
-#endif
-
- /* Record the number of times that we do a normal fsync() and
- ** FULLSYNC. This is used during testing to verify that this procedure
- ** gets called with the correct arguments.
- */
-#ifdef SQLITE_TEST
- if( fullSync ) sqlite3_fullsync_count++;
- sqlite3_sync_count++;
-#endif
-
- /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
- ** no-op. But go ahead and call fstat() to validate the file
- ** descriptor as we need a method to provoke a failure during
- ** coverate testing.
- */
-#ifdef SQLITE_NO_SYNC
- {
- struct stat buf;
- rc = osFstat(fd, &buf);
- }
-#elif HAVE_FULLFSYNC
- if( fullSync ){
- rc = osFcntl(fd, F_FULLFSYNC, 0);
- }else{
- rc = 1;
- }
- /* If the FULLFSYNC failed, fall back to attempting an fsync().
- ** It shouldn't be possible for fullfsync to fail on the local
- ** file system (on OSX), so failure indicates that FULLFSYNC
- ** isn't supported for this file system. So, attempt an fsync
- ** and (for now) ignore the overhead of a superfluous fcntl call.
- ** It'd be better to detect fullfsync support once and avoid
- ** the fcntl call every time sync is called.
- */
- if( rc ) rc = fsync(fd);
-
-#elif defined(__APPLE__)
- /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
- ** so currently we default to the macro that redefines fdatasync to fsync
- */
- rc = fsync(fd);
-#else
- rc = fdatasync(fd);
-#if OS_VXWORKS
- if( rc==-1 && errno==ENOTSUP ){
- rc = fsync(fd);
- }
-#endif /* OS_VXWORKS */
-#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
-
- if( OS_VXWORKS && rc!= -1 ){
- rc = 0;
- }
- return rc;
-}
-
-/*
-** Open a file descriptor to the directory containing file zFilename.
-** If successful, *pFd is set to the opened file descriptor and
-** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
-** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
-** value.
-**
-** The directory file descriptor is used for only one thing - to
-** fsync() a directory to make sure file creation and deletion events
-** are flushed to disk. Such fsyncs are not needed on newer
-** journaling filesystems, but are required on older filesystems.
-**
-** This routine can be overridden using the xSetSysCall interface.
-** The ability to override this routine was added in support of the
-** chromium sandbox. Opening a directory is a security risk (we are
-** told) so making it overrideable allows the chromium sandbox to
-** replace this routine with a harmless no-op. To make this routine
-** a no-op, replace it with a stub that returns SQLITE_OK but leaves
-** *pFd set to a negative number.
-**
-** If SQLITE_OK is returned, the caller is responsible for closing
-** the file descriptor *pFd using close().
-*/
-static int openDirectory(const char *zFilename, int *pFd){
- int ii;
- int fd = -1;
- char zDirname[MAX_PATHNAME+1];
-
- sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
- for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
- if( ii>0 ){
- zDirname[ii] = '\0';
- }else{
- if( zDirname[0]!='/' ) zDirname[0] = '.';
- zDirname[1] = 0;
- }
- fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
- if( fd>=0 ){
- OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
- }
- *pFd = fd;
- if( fd>=0 ) return SQLITE_OK;
- return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
-}
-
-/*
-** Make sure all writes to a particular file are committed to disk.
-**
-** If dataOnly==0 then both the file itself and its metadata (file
-** size, access time, etc) are synced. If dataOnly!=0 then only the
-** file data is synced.
-**
-** Under Unix, also make sure that the directory entry for the file
-** has been created by fsync-ing the directory that contains the file.
-** If we do not do this and we encounter a power failure, the directory
-** entry for the journal might not exist after we reboot. The next
-** SQLite to access the file will not know that the journal exists (because
-** the directory entry for the journal was never created) and the transaction
-** will not roll back - possibly leading to database corruption.
-*/
-static int unixSync(sqlite3_file *id, int flags){
- int rc;
- unixFile *pFile = (unixFile*)id;
-
- int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
- int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
-
- /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
- assert((flags&0x0F)==SQLITE_SYNC_NORMAL
- || (flags&0x0F)==SQLITE_SYNC_FULL
- );
-
- /* Unix cannot, but some systems may return SQLITE_FULL from here. This
- ** line is to test that doing so does not cause any problems.
- */
- SimulateDiskfullError( return SQLITE_FULL );
-
- assert( pFile );
- OSTRACE(("SYNC %-3d\n", pFile->h));
- rc = full_fsync(pFile->h, isFullsync, isDataOnly);
- SimulateIOError( rc=1 );
- if( rc ){
- storeLastErrno(pFile, errno);
- return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
- }
-
- /* Also fsync the directory containing the file if the DIRSYNC flag
- ** is set. This is a one-time occurrence. Many systems (examples: AIX)
- ** are unable to fsync a directory, so ignore errors on the fsync.
- */
- if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
- int dirfd;
- OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
- HAVE_FULLFSYNC, isFullsync));
- rc = osOpenDirectory(pFile->zPath, &dirfd);
- if( rc==SQLITE_OK ){
- full_fsync(dirfd, 0, 0);
- robust_close(pFile, dirfd, __LINE__);
- }else{
- assert( rc==SQLITE_CANTOPEN );
- rc = SQLITE_OK;
- }
- pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
- }
- return rc;
-}
-
-/*
-** Truncate an open file to a specified size
-*/
-static int unixTruncate(sqlite3_file *id, i64 nByte){
- unixFile *pFile = (unixFile *)id;
- int rc;
- assert( pFile );
- SimulateIOError( return SQLITE_IOERR_TRUNCATE );
-
- /* 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;
- }
-
- rc = robust_ftruncate(pFile->h, nByte);
- if( rc ){
- storeLastErrno(pFile, errno);
- return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
- }else{
-#ifdef SQLITE_DEBUG
- /* If we are doing a normal write to a database file (as opposed to
- ** doing a hot-journal rollback or a write to some file other than a
- ** normal database file) and we truncate the file to zero length,
- ** that effectively updates the change counter. This might happen
- ** when restoring a database using the backup API from a zero-length
- ** source.
- */
- if( pFile->inNormalWrite && nByte==0 ){
- pFile->transCntrChng = 1;
- }
-#endif
-
-#if SQLITE_MAX_MMAP_SIZE>0
- /* If the file was just truncated to a size smaller than the currently
- ** mapped region, reduce the effective mapping size as well. SQLite will
- ** use read() and write() to access data beyond this point from now on.
- */
- if( nBytemmapSize ){
- pFile->mmapSize = nByte;
- }
-#endif
-
- return SQLITE_OK;
- }
-}
-
-/*
-** Determine the current size of a file in bytes
-*/
-static int unixFileSize(sqlite3_file *id, i64 *pSize){
- int rc;
- struct stat buf;
- assert( id );
- rc = osFstat(((unixFile*)id)->h, &buf);
- SimulateIOError( rc=1 );
- if( rc!=0 ){
- storeLastErrno((unixFile*)id, errno);
- return SQLITE_IOERR_FSTAT;
- }
- *pSize = buf.st_size;
-
- /* When opening a zero-size database, the findInodeInfo() procedure
- ** writes a single byte into that file in order to work around a bug
- ** in the OS-X msdos filesystem. In order to avoid problems with upper
- ** layers, we need to report this file size as zero even though it is
- ** really 1. Ticket #3260.
- */
- if( *pSize==1 ) *pSize = 0;
-
-
- return SQLITE_OK;
-}
-
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
-/*
-** Handler for proxy-locking file-control verbs. Defined below in the
-** proxying locking division.
-*/
-static int proxyFileControl(sqlite3_file*,int,void*);
-#endif
-
-/*
-** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
-** file-control operation. Enlarge the database to nBytes in size
-** (rounded up to the next chunk-size). If the database is already
-** nBytes or larger, this routine is a no-op.
-*/
-static int fcntlSizeHint(unixFile *pFile, i64 nByte){
- if( pFile->szChunk>0 ){
- i64 nSize; /* Required file size */
- struct stat buf; /* Used to hold return values of fstat() */
-
- if( osFstat(pFile->h, &buf) ){
- return SQLITE_IOERR_FSTAT;
- }
-
- nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
- if( nSize>(i64)buf.st_size ){
-
-#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
- /* The code below is handling the return value of osFallocate()
- ** correctly. posix_fallocate() is defined to "returns zero on success,
- ** or an error number on failure". See the manpage for details. */
- int err;
- do{
- err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
- }while( err==EINTR );
- if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
-#else
- /* If the OS does not have posix_fallocate(), fake it. Write a
- ** single byte to the last byte in each block that falls entirely
- ** within the extended region. Then, if required, a single byte
- ** at offset (nSize-1), to set the size of the file correctly.
- ** This is a similar technique to that used by glibc on systems
- ** that do not have a real fallocate() call.
- */
- int nBlk = buf.st_blksize; /* File-system block size */
- int nWrite = 0; /* Number of bytes written by seekAndWrite */
- i64 iWrite; /* Next offset to write to */
-
- iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
- assert( iWrite>=buf.st_size );
- assert( ((iWrite+1)%nBlk)==0 );
- for(/*no-op*/; iWrite=nSize ) iWrite = nSize - 1;
- nWrite = seekAndWrite(pFile, iWrite, "", 1);
- if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
- }
-#endif
- }
- }
-
-#if SQLITE_MAX_MMAP_SIZE>0
- if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
- int rc;
- if( pFile->szChunk<=0 ){
- if( robust_ftruncate(pFile->h, nByte) ){
- storeLastErrno(pFile, errno);
- return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
- }
- }
-
- rc = unixMapfile(pFile, nByte);
- return rc;
- }
-#endif
-
- return SQLITE_OK;
-}
-
-/*
-** If *pArg is initially negative then this is a query. Set *pArg to
-** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
-**
-** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
-*/
-static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
- if( *pArg<0 ){
- *pArg = (pFile->ctrlFlags & mask)!=0;
- }else if( (*pArg)==0 ){
- pFile->ctrlFlags &= ~mask;
- }else{
- pFile->ctrlFlags |= mask;
- }
-}
-
-/* Forward declaration */
-static int unixGetTempname(int nBuf, char *zBuf);
-
-/*
-** Information and control of an open file handle.
-*/
-static int unixFileControl(sqlite3_file *id, int op, void *pArg){
- unixFile *pFile = (unixFile*)id;
- switch( op ){
-#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
- case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
- int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
- return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
- }
- case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
- int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
- return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
- }
- case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
- int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
- return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
- }
-#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
-
- case SQLITE_FCNTL_LOCKSTATE: {
- *(int*)pArg = pFile->eFileLock;
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_LAST_ERRNO: {
- *(int*)pArg = pFile->lastErrno;
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_CHUNK_SIZE: {
- pFile->szChunk = *(int *)pArg;
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_SIZE_HINT: {
- int rc;
- SimulateIOErrorBenign(1);
- rc = fcntlSizeHint(pFile, *(i64 *)pArg);
- SimulateIOErrorBenign(0);
- return rc;
- }
- case SQLITE_FCNTL_PERSIST_WAL: {
- unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
- unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_VFSNAME: {
- *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_TEMPFILENAME: {
- char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
- if( zTFile ){
- unixGetTempname(pFile->pVfs->mxPathname, zTFile);
- *(char**)pArg = zTFile;
- }
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_HAS_MOVED: {
- *(int*)pArg = fileHasMoved(pFile);
- return SQLITE_OK;
- }
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
- case SQLITE_FCNTL_LOCK_TIMEOUT: {
- pFile->iBusyTimeout = *(int*)pArg;
- return SQLITE_OK;
- }
-#endif
-#if SQLITE_MAX_MMAP_SIZE>0
- case SQLITE_FCNTL_MMAP_SIZE: {
- i64 newLimit = *(i64*)pArg;
- int rc = SQLITE_OK;
- if( newLimit>sqlite3GlobalConfig.mxMmap ){
- newLimit = sqlite3GlobalConfig.mxMmap;
- }
-
- /* The value of newLimit may be eventually cast to (size_t) and passed
- ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
- ** 64-bit type. */
- if( newLimit>0 && sizeof(size_t)<8 ){
- newLimit = (newLimit & 0x7FFFFFFF);
- }
-
- *(i64*)pArg = pFile->mmapSizeMax;
- if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
- pFile->mmapSizeMax = newLimit;
- if( pFile->mmapSize>0 ){
- unixUnmapfile(pFile);
- rc = unixMapfile(pFile, -1);
- }
- }
- return rc;
- }
-#endif
-#ifdef SQLITE_DEBUG
- /* The pager calls this method to signal that it has done
- ** a rollback and that the database is therefore unchanged and
- ** it hence it is OK for the transaction change counter to be
- ** unchanged.
- */
- case SQLITE_FCNTL_DB_UNCHANGED: {
- ((unixFile*)id)->dbUpdate = 0;
- return SQLITE_OK;
- }
-#endif
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
- case SQLITE_FCNTL_SET_LOCKPROXYFILE:
- case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
- return proxyFileControl(id,op,pArg);
- }
-#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
- }
- return SQLITE_NOTFOUND;
-}
-
-/*
-** If pFd->sectorSize is non-zero when this function is called, it is a
-** no-op. Otherwise, the values of pFd->sectorSize and
-** pFd->deviceCharacteristics are set according to the file-system
-** characteristics.
-**
-** There are two versions of this function. One for QNX and one for all
-** other systems.
-*/
-#ifndef __QNXNTO__
-static void setDeviceCharacteristics(unixFile *pFd){
- assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
- if( pFd->sectorSize==0 ){
-#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
- int res;
- u32 f = 0;
-
- /* Check for support for F2FS atomic batch writes. */
- res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
- if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
- pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
- }
-#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
-
- /* Set the POWERSAFE_OVERWRITE flag if requested. */
- if( pFd->ctrlFlags & UNIXFILE_PSOW ){
- pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
- }
-
- pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
- }
-}
-#else
-#include
-#include
-static void setDeviceCharacteristics(unixFile *pFile){
- if( pFile->sectorSize == 0 ){
- struct statvfs fsInfo;
-
- /* Set defaults for non-supported filesystems */
- pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
- pFile->deviceCharacteristics = 0;
- if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
- return;
- }
-
- if( !strcmp(fsInfo.f_basetype, "tmp") ) {
- pFile->sectorSize = fsInfo.f_bsize;
- pFile->deviceCharacteristics =
- SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
- SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
- ** the write succeeds */
- SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
- ** so it is ordered */
- 0;
- }else if( strstr(fsInfo.f_basetype, "etfs") ){
- pFile->sectorSize = fsInfo.f_bsize;
- pFile->deviceCharacteristics =
- /* etfs cluster size writes are atomic */
- (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
- SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
- ** the write succeeds */
- SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
- ** so it is ordered */
- 0;
- }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
- pFile->sectorSize = fsInfo.f_bsize;
- pFile->deviceCharacteristics =
- SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
- SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
- ** the write succeeds */
- SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
- ** so it is ordered */
- 0;
- }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
- pFile->sectorSize = fsInfo.f_bsize;
- pFile->deviceCharacteristics =
- /* full bitset of atomics from max sector size and smaller */
- ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
- SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
- ** so it is ordered */
- 0;
- }else if( strstr(fsInfo.f_basetype, "dos") ){
- pFile->sectorSize = fsInfo.f_bsize;
- pFile->deviceCharacteristics =
- /* full bitset of atomics from max sector size and smaller */
- ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
- SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
- ** so it is ordered */
- 0;
- }else{
- pFile->deviceCharacteristics =
- SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
- SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
- ** the write succeeds */
- 0;
- }
- }
- /* Last chance verification. If the sector size isn't a multiple of 512
- ** then it isn't valid.*/
- if( pFile->sectorSize % 512 != 0 ){
- pFile->deviceCharacteristics = 0;
- pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
- }
-}
-#endif
-
-/*
-** 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 unixSectorSize(sqlite3_file *id){
- unixFile *pFd = (unixFile*)id;
- setDeviceCharacteristics(pFd);
- return pFd->sectorSize;
-}
-
-/*
-** Return the device characteristics for the file.
-**
-** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
-** However, that choice is controversial since technically the underlying
-** file system does not always provide powersafe overwrites. (In other
-** words, after a power-loss event, parts of the file that were never
-** written might end up being altered.) However, non-PSOW behavior is very,
-** very rare. And asserting PSOW makes a large reduction in the amount
-** of required I/O for journaling, since a lot of padding is eliminated.
-** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
-** available to turn it off and URI query parameter available to turn it off.
-*/
-static int unixDeviceCharacteristics(sqlite3_file *id){
- unixFile *pFd = (unixFile*)id;
- setDeviceCharacteristics(pFd);
- return pFd->deviceCharacteristics;
-}
-
-#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
-
-/*
-** Return the system page size.
-**
-** This function should not be called directly by other code in this file.
-** Instead, it should be called via macro osGetpagesize().
-*/
-static int unixGetpagesize(void){
-#if OS_VXWORKS
- return 1024;
-#elif defined(_BSD_SOURCE)
- return getpagesize();
-#else
- return (int)sysconf(_SC_PAGESIZE);
-#endif
-}
-
-#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
-
-#ifndef SQLITE_OMIT_WAL
-
-/*
-** Object used to represent an shared memory buffer.
-**
-** When multiple threads all reference the same wal-index, each thread
-** has its own unixShm object, but they all point to a single instance
-** of this unixShmNode object. In other words, each wal-index is opened
-** only once per process.
-**
-** Each unixShmNode object is connected to a single unixInodeInfo object.
-** We could coalesce this object into unixInodeInfo, but that would mean
-** every open file that does not use shared memory (in other words, most
-** open files) would have to carry around this extra information. So
-** the unixInodeInfo object contains a pointer to this unixShmNode object
-** and the unixShmNode object is created only when needed.
-**
-** unixMutexHeld() must be true when creating or destroying
-** this object or while reading or writing the following fields:
-**
-** nRef
-**
-** The following fields are read-only after the object is created:
-**
-** hShm
-** zFilename
-**
-** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
-** unixMutexHeld() is true when reading or writing any other field
-** in this structure.
-*/
-struct unixShmNode {
- unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
- sqlite3_mutex *pShmMutex; /* Mutex to access this object */
- char *zFilename; /* Name of the mmapped file */
- int hShm; /* Open file descriptor */
- int szRegion; /* Size of shared-memory regions */
- u16 nRegion; /* Size of array apRegion */
- u8 isReadonly; /* True if read-only */
- u8 isUnlocked; /* True if no DMS lock held */
- char **apRegion; /* Array of mapped shared-memory regions */
- int nRef; /* Number of unixShm objects pointing to this */
- unixShm *pFirst; /* All unixShm objects pointing to this */
-#ifdef SQLITE_DEBUG
- u8 exclMask; /* Mask of exclusive locks held */
- u8 sharedMask; /* Mask of shared locks held */
- u8 nextShmId; /* Next available unixShm.id value */
-#endif
-};
-
-/*
-** 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:
-**
-** unixShm.pShmNode
-** unixShm.id
-**
-** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
-** be held while accessing any read/write fields.
-*/
-struct unixShm {
- unixShmNode *pShmNode; /* The underlying unixShmNode object */
- unixShm *pNext; /* Next unixShm with the same unixShmNode */
- u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
- u8 id; /* Id of this connection within its unixShmNode */
- u16 sharedMask; /* Mask of shared locks held */
- u16 exclMask; /* Mask of exclusive locks held */
-};
-
-/*
-** Constants used for locking
-*/
-#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
-#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
-
-/*
-** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
-**
-** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
-** otherwise.
-*/
-static int unixShmSystemLock(
- unixFile *pFile, /* Open connection to the WAL file */
- int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
- int ofst, /* First byte of the locking range */
- int n /* Number of bytes to lock */
-){
- unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
- struct flock f; /* The posix advisory locking structure */
- int rc = SQLITE_OK; /* Result code form fcntl() */
-
- /* Access to the unixShmNode object is serialized by the caller */
- pShmNode = pFile->pInode->pShmNode;
- assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
- assert( pShmNode->nRef>0 || unixMutexHeld() );
-
- /* Shared locks never span more than one byte */
- assert( n==1 || lockType!=F_RDLCK );
-
- /* Locks are within range */
- assert( n>=1 && n<=SQLITE_SHM_NLOCK );
-
- if( pShmNode->hShm>=0 ){
- /* Initialize the locking parameters */
- f.l_type = lockType;
- f.l_whence = SEEK_SET;
- f.l_start = ofst;
- f.l_len = n;
- rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
- rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
- }
-
- /* Update the global lock state and do debug tracing */
-#ifdef SQLITE_DEBUG
- { u16 mask;
- OSTRACE(("SHM-LOCK "));
- mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<exclMask &= ~mask;
- pShmNode->sharedMask &= ~mask;
- }else if( lockType==F_RDLCK ){
- OSTRACE(("read-lock %d ok", ofst));
- pShmNode->exclMask &= ~mask;
- pShmNode->sharedMask |= mask;
- }else{
- assert( lockType==F_WRLCK );
- OSTRACE(("write-lock %d ok", ofst));
- pShmNode->exclMask |= mask;
- pShmNode->sharedMask &= ~mask;
- }
- }else{
- if( lockType==F_UNLCK ){
- OSTRACE(("unlock %d failed", ofst));
- }else if( lockType==F_RDLCK ){
- OSTRACE(("read-lock failed"));
- }else{
- assert( lockType==F_WRLCK );
- OSTRACE(("write-lock %d failed", ofst));
- }
- }
- OSTRACE((" - afterwards %03x,%03x\n",
- pShmNode->sharedMask, pShmNode->exclMask));
- }
-#endif
-
- return rc;
-}
-
-/*
-** Return the minimum number of 32KB shm regions that should be mapped at
-** a time, assuming that each mapping must be an integer multiple of the
-** current system page-size.
-**
-** Usually, this is 1. The exception seems to be systems that are configured
-** to use 64KB pages - in this case each mapping must cover at least two
-** shm regions.
-*/
-static int unixShmRegionPerMap(void){
- int shmsz = 32*1024; /* SHM region size */
- int pgsz = osGetpagesize(); /* System page size */
- assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
- if( pgszpInode->pShmNode;
- assert( unixMutexHeld() );
- if( p && ALWAYS(p->nRef==0) ){
- int nShmPerMap = unixShmRegionPerMap();
- int i;
- assert( p->pInode==pFd->pInode );
- sqlite3_mutex_free(p->pShmMutex);
- for(i=0; inRegion; i+=nShmPerMap){
- if( p->hShm>=0 ){
- osMunmap(p->apRegion[i], p->szRegion);
- }else{
- sqlite3_free(p->apRegion[i]);
- }
- }
- sqlite3_free(p->apRegion);
- if( p->hShm>=0 ){
- robust_close(pFd, p->hShm, __LINE__);
- p->hShm = -1;
- }
- p->pInode->pShmNode = 0;
- sqlite3_free(p);
- }
-}
-
-/*
-** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
-** take it now. Return SQLITE_OK if successful, or an SQLite error
-** code otherwise.
-**
-** If the DMS cannot be locked because this is a readonly_shm=1
-** connection and no other process already holds a lock, return
-** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
-*/
-static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
- struct flock lock;
- int rc = SQLITE_OK;
-
- /* Use F_GETLK to determine the locks other processes are holding
- ** on the DMS byte. If it indicates that another process is holding
- ** a SHARED lock, then this process may also take a SHARED lock
- ** and proceed with opening the *-shm file.
- **
- ** Or, if no other process is holding any lock, then this process
- ** is the first to open it. In this case take an EXCLUSIVE lock on the
- ** DMS byte and truncate the *-shm file to zero bytes in size. Then
- ** downgrade to a SHARED lock on the DMS byte.
- **
- ** If another process is holding an EXCLUSIVE lock on the DMS byte,
- ** return SQLITE_BUSY to the caller (it will try again). An earlier
- ** version of this code attempted the SHARED lock at this point. But
- ** this introduced a subtle race condition: if the process holding
- ** EXCLUSIVE failed just before truncating the *-shm file, then this
- ** process might open and use the *-shm file without truncating it.
- ** And if the *-shm file has been corrupted by a power failure or
- ** system crash, the database itself may also become corrupt. */
- lock.l_whence = SEEK_SET;
- lock.l_start = UNIX_SHM_DMS;
- lock.l_len = 1;
- lock.l_type = F_WRLCK;
- if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
- rc = SQLITE_IOERR_LOCK;
- }else if( lock.l_type==F_UNLCK ){
- if( pShmNode->isReadonly ){
- pShmNode->isUnlocked = 1;
- rc = SQLITE_READONLY_CANTINIT;
- }else{
- rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
- /* The first connection to attach must truncate the -shm file. We
- ** truncate to 3 bytes (an arbitrary small number, less than the
- ** -shm header size) rather than 0 as a system debugging aid, to
- ** help detect if a -shm file truncation is legitimate or is the work
- ** or a rogue process. */
- if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
- rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
- }
- }
- }else if( lock.l_type==F_WRLCK ){
- rc = SQLITE_BUSY;
- }
-
- if( rc==SQLITE_OK ){
- assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
- rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
- }
- return rc;
-}
-
-/*
-** Open a shared-memory area associated with open database file pDbFd.
-** This particular implementation uses mmapped files.
-**
-** The file used to implement shared-memory is in the same directory
-** as the open database file and has the same name as the open database
-** file with the "-shm" suffix added. For example, if the database file
-** is "/home/user1/config.db" then the file that is created and mmapped
-** for shared memory will be called "/home/user1/config.db-shm".
-**
-** Another approach to is to use files in /dev/shm or /dev/tmp or an
-** some other tmpfs mount. But if a file in a different directory
-** from the database file is used, then differing access permissions
-** or a chroot() might cause two different processes on the same
-** database to end up using different files for shared memory -
-** meaning that their memory would not really be shared - resulting
-** in database corruption. Nevertheless, this tmpfs file usage
-** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
-** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
-** option results in an incompatible build of SQLite; builds of SQLite
-** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
-** same database file at the same time, database corruption will likely
-** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
-** "unsupported" and may go away in a future SQLite release.
-**
-** 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.
-**
-** If the original database file (pDbFd) is using the "unix-excl" VFS
-** that means that an exclusive lock is held on the database file and
-** that no other processes are able to read or write the database. In
-** that case, we do not really need shared memory. No shared memory
-** file is created. The shared memory will be simulated with heap memory.
-*/
-static int unixOpenSharedMemory(unixFile *pDbFd){
- struct unixShm *p = 0; /* The connection to be opened */
- struct unixShmNode *pShmNode; /* The underlying mmapped file */
- int rc = SQLITE_OK; /* Result code */
- unixInodeInfo *pInode; /* The inode of fd */
- char *zShm; /* Name of the file used for SHM */
- int nShmFilename; /* Size of the SHM filename in bytes */
-
- /* Allocate space for the new unixShm object. */
- p = sqlite3_malloc64( sizeof(*p) );
- if( p==0 ) return SQLITE_NOMEM_BKPT;
- memset(p, 0, sizeof(*p));
- assert( pDbFd->pShm==0 );
-
- /* Check to see if a unixShmNode object already exists. Reuse an existing
- ** one if present. Create a new one if necessary.
- */
- assert( unixFileMutexNotheld(pDbFd) );
- unixEnterMutex();
- pInode = pDbFd->pInode;
- pShmNode = pInode->pShmNode;
- if( pShmNode==0 ){
- struct stat sStat; /* fstat() info for database file */
-#ifndef SQLITE_SHM_DIRECTORY
- const char *zBasePath = pDbFd->zPath;
-#endif
-
- /* Call fstat() to figure out the permissions on the database file. If
- ** a new *-shm file is created, an attempt will be made to create it
- ** with the same permissions.
- */
- if( osFstat(pDbFd->h, &sStat) ){
- rc = SQLITE_IOERR_FSTAT;
- goto shm_open_err;
- }
-
-#ifdef SQLITE_SHM_DIRECTORY
- nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
-#else
- nShmFilename = 6 + (int)strlen(zBasePath);
-#endif
- pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
- if( pShmNode==0 ){
- rc = SQLITE_NOMEM_BKPT;
- goto shm_open_err;
- }
- memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
- zShm = pShmNode->zFilename = (char*)&pShmNode[1];
-#ifdef SQLITE_SHM_DIRECTORY
- sqlite3_snprintf(nShmFilename, zShm,
- SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
- (u32)sStat.st_ino, (u32)sStat.st_dev);
-#else
- sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
- sqlite3FileSuffix3(pDbFd->zPath, zShm);
-#endif
- pShmNode->hShm = -1;
- pDbFd->pInode->pShmNode = pShmNode;
- pShmNode->pInode = pDbFd->pInode;
- if( sqlite3GlobalConfig.bCoreMutex ){
- pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
- if( pShmNode->pShmMutex==0 ){
- rc = SQLITE_NOMEM_BKPT;
- goto shm_open_err;
- }
- }
-
- if( pInode->bProcessLock==0 ){
- if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
- pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
- }
- if( pShmNode->hShm<0 ){
- pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
- if( pShmNode->hShm<0 ){
- rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
- goto shm_open_err;
- }
- pShmNode->isReadonly = 1;
- }
-
- /* If this process is running as root, make sure that the SHM file
- ** is owned by the same user that owns the original database. Otherwise,
- ** the original owner will not be able to connect.
- */
- robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
-
- rc = unixLockSharedMemory(pDbFd, pShmNode);
- if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
- }
- }
-
- /* Make the new connection a child of the unixShmNode */
- p->pShmNode = pShmNode;
-#ifdef SQLITE_DEBUG
- p->id = pShmNode->nextShmId++;
-#endif
- pShmNode->nRef++;
- pDbFd->pShm = p;
- unixLeaveMutex();
-
- /* The reference count on pShmNode has already been incremented under
- ** the cover of the unixEnterMutex() mutex and the pointer from the
- ** new (struct unixShm) 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->pShmMutex.
- */
- sqlite3_mutex_enter(pShmNode->pShmMutex);
- p->pNext = pShmNode->pFirst;
- pShmNode->pFirst = p;
- sqlite3_mutex_leave(pShmNode->pShmMutex);
- return rc;
-
- /* Jump here on any error */
-shm_open_err:
- unixShmPurge(pDbFd); /* This call frees pShmNode if required */
- sqlite3_free(p);
- unixLeaveMutex();
- return rc;
-}
-
-/*
-** 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 bExtend 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
-** bExtend 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 unixShmMap(
- sqlite3_file *fd, /* Handle open on database file */
- int iRegion, /* Region to retrieve */
- int szRegion, /* Size of regions */
- int bExtend, /* True to extend file if necessary */
- void volatile **pp /* OUT: Mapped memory */
-){
- unixFile *pDbFd = (unixFile*)fd;
- unixShm *p;
- unixShmNode *pShmNode;
- int rc = SQLITE_OK;
- int nShmPerMap = unixShmRegionPerMap();
- int nReqRegion;
-
- /* If the shared-memory file has not yet been opened, open it now. */
- if( pDbFd->pShm==0 ){
- rc = unixOpenSharedMemory(pDbFd);
- if( rc!=SQLITE_OK ) return rc;
- }
-
- p = pDbFd->pShm;
- pShmNode = p->pShmNode;
- sqlite3_mutex_enter(pShmNode->pShmMutex);
- if( pShmNode->isUnlocked ){
- rc = unixLockSharedMemory(pDbFd, pShmNode);
- if( rc!=SQLITE_OK ) goto shmpage_out;
- pShmNode->isUnlocked = 0;
- }
- assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
- assert( pShmNode->pInode==pDbFd->pInode );
- assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
- assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
-
- /* Minimum number of regions required to be mapped. */
- nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
-
- if( pShmNode->nRegionszRegion = szRegion;
-
- if( pShmNode->hShm>=0 ){
- /* 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).
- */
- if( osFstat(pShmNode->hShm, &sStat) ){
- rc = SQLITE_IOERR_SHMSIZE;
- goto shmpage_out;
- }
-
- if( sStat.st_sizehShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
- const char *zFile = pShmNode->zFilename;
- rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
- goto shmpage_out;
- }
- }
- }
- }
- }
-
- /* Map the requested memory region into this processes address space. */
- apNew = (char **)sqlite3_realloc(
- pShmNode->apRegion, nReqRegion*sizeof(char *)
- );
- if( !apNew ){
- rc = SQLITE_IOERR_NOMEM_BKPT;
- goto shmpage_out;
- }
- pShmNode->apRegion = apNew;
- while( pShmNode->nRegionhShm>=0 ){
- pMem = osMmap(0, nMap,
- pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
- MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
- );
- if( pMem==MAP_FAILED ){
- rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
- goto shmpage_out;
- }
- }else{
- pMem = sqlite3_malloc64(nMap);
- if( pMem==0 ){
- rc = SQLITE_NOMEM_BKPT;
- goto shmpage_out;
- }
- memset(pMem, 0, nMap);
- }
-
- for(i=0; iapRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
- }
- pShmNode->nRegion += nShmPerMap;
- }
- }
-
-shmpage_out:
- if( pShmNode->nRegion>iRegion ){
- *pp = pShmNode->apRegion[iRegion];
- }else{
- *pp = 0;
- }
- if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
- sqlite3_mutex_leave(pShmNode->pShmMutex);
- return rc;
-}
-
-/*
-** Change the lock state for a shared-memory segment.
-**
-** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
-** different here than in posix. In xShmLock(), one can go from unlocked
-** to shared and back or from unlocked to exclusive and back. But one may
-** not go from shared to exclusive or from exclusive to shared.
-*/
-static int unixShmLock(
- 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 */
-){
- unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
- unixShm *p = pDbFd->pShm; /* The shared memory being locked */
- unixShm *pX; /* For looping over all siblings */
- unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
- int rc = SQLITE_OK; /* Result code */
- u16 mask; /* Mask of locks to take or release */
-
- assert( pShmNode==pDbFd->pInode->pShmNode );
- assert( pShmNode->pInode==pDbFd->pInode );
- assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
- assert( n>=1 );
- 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) );
- assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
- assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
- assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
-
- mask = (1<<(ofst+n)) - (1<1 || mask==(1<pShmMutex);
- 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;
- assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
- allMask |= pX->sharedMask;
- }
-
- /* Unlock the system-level locks */
- if( (mask & allMask)==0 ){
- rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_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 = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_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 = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
- if( rc==SQLITE_OK ){
- assert( (p->sharedMask & mask)==0 );
- p->exclMask |= mask;
- }
- }
- }
- sqlite3_mutex_leave(pShmNode->pShmMutex);
- OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
- p->id, osGetpid(0), p->sharedMask, p->exclMask));
- 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 unixShmBarrier(
- sqlite3_file *fd /* Database file holding the shared memory */
-){
- UNUSED_PARAMETER(fd);
- sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
- assert( fd->pMethods->xLock==nolockLock
- || unixFileMutexNotheld((unixFile*)fd)
- );
- unixEnterMutex(); /* Also mutex, for redundancy */
- unixLeaveMutex();
-}
-
-/*
-** Close a connection to shared-memory. Delete the underlying
-** storage if deleteFlag is true.
-**
-** If there is no shared memory associated with the connection then this
-** routine is a harmless no-op.
-*/
-static int unixShmUnmap(
- sqlite3_file *fd, /* The underlying database file */
- int deleteFlag /* Delete shared-memory if true */
-){
- unixShm *p; /* The connection to be closed */
- unixShmNode *pShmNode; /* The underlying shared-memory file */
- unixShm **pp; /* For looping over sibling connections */
- unixFile *pDbFd; /* The underlying database file */
-
- pDbFd = (unixFile*)fd;
- p = pDbFd->pShm;
- if( p==0 ) return SQLITE_OK;
- pShmNode = p->pShmNode;
-
- assert( pShmNode==pDbFd->pInode->pShmNode );
- assert( pShmNode->pInode==pDbFd->pInode );
-
- /* Remove connection p from the set of connections associated
- ** with pShmNode */
- sqlite3_mutex_enter(pShmNode->pShmMutex);
- 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->pShmMutex);
-
- /* If pShmNode->nRef has reached 0, then close the underlying
- ** shared-memory file, too */
- assert( unixFileMutexNotheld(pDbFd) );
- unixEnterMutex();
- assert( pShmNode->nRef>0 );
- pShmNode->nRef--;
- if( pShmNode->nRef==0 ){
- if( deleteFlag && pShmNode->hShm>=0 ){
- osUnlink(pShmNode->zFilename);
- }
- unixShmPurge(pDbFd);
- }
- unixLeaveMutex();
-
- return SQLITE_OK;
-}
-
-
-#else
-# define unixShmMap 0
-# define unixShmLock 0
-# define unixShmBarrier 0
-# define unixShmUnmap 0
-#endif /* #ifndef SQLITE_OMIT_WAL */
-
-#if SQLITE_MAX_MMAP_SIZE>0
-/*
-** If it is currently memory mapped, unmap file pFd.
-*/
-static void unixUnmapfile(unixFile *pFd){
- assert( pFd->nFetchOut==0 );
- if( pFd->pMapRegion ){
- osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
- pFd->pMapRegion = 0;
- pFd->mmapSize = 0;
- pFd->mmapSizeActual = 0;
- }
-}
-
-/*
-** Attempt to set the size of the memory mapping maintained by file
-** descriptor pFd to nNew bytes. Any existing mapping is discarded.
-**
-** If successful, this function sets the following variables:
-**
-** unixFile.pMapRegion
-** unixFile.mmapSize
-** unixFile.mmapSizeActual
-**
-** If unsuccessful, an error message is logged via sqlite3_log() and
-** the three variables above are zeroed. In this case SQLite should
-** continue accessing the database using the xRead() and xWrite()
-** methods.
-*/
-static void unixRemapfile(
- unixFile *pFd, /* File descriptor object */
- i64 nNew /* Required mapping size */
-){
- const char *zErr = "mmap";
- int h = pFd->h; /* File descriptor open on db file */
- u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
- i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
- u8 *pNew = 0; /* Location of new mapping */
- int flags = PROT_READ; /* Flags to pass to mmap() */
-
- assert( pFd->nFetchOut==0 );
- assert( nNew>pFd->mmapSize );
- assert( nNew<=pFd->mmapSizeMax );
- assert( nNew>0 );
- assert( pFd->mmapSizeActual>=pFd->mmapSize );
- assert( MAP_FAILED!=0 );
-
-#ifdef SQLITE_MMAP_READWRITE
- if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
-#endif
-
- if( pOrig ){
-#if HAVE_MREMAP
- i64 nReuse = pFd->mmapSize;
-#else
- const int szSyspage = osGetpagesize();
- i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
-#endif
- u8 *pReq = &pOrig[nReuse];
-
- /* Unmap any pages of the existing mapping that cannot be reused. */
- if( nReuse!=nOrig ){
- osMunmap(pReq, nOrig-nReuse);
- }
-
-#if HAVE_MREMAP
- pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
- zErr = "mremap";
-#else
- pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
- if( pNew!=MAP_FAILED ){
- if( pNew!=pReq ){
- osMunmap(pNew, nNew - nReuse);
- pNew = 0;
- }else{
- pNew = pOrig;
- }
- }
-#endif
-
- /* The attempt to extend the existing mapping failed. Free it. */
- if( pNew==MAP_FAILED || pNew==0 ){
- osMunmap(pOrig, nReuse);
- }
- }
-
- /* If pNew is still NULL, try to create an entirely new mapping. */
- if( pNew==0 ){
- pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
- }
-
- if( pNew==MAP_FAILED ){
- pNew = 0;
- nNew = 0;
- unixLogError(SQLITE_OK, zErr, pFd->zPath);
-
- /* If the mmap() above failed, assume that all subsequent mmap() calls
- ** will probably fail too. Fall back to using xRead/xWrite exclusively
- ** in this case. */
- pFd->mmapSizeMax = 0;
- }
- pFd->pMapRegion = (void *)pNew;
- pFd->mmapSize = pFd->mmapSizeActual = nNew;
-}
-
-/*
-** Memory map or remap the file opened by file-descriptor pFd (if the file
-** is already mapped, the existing mapping is replaced by the new). Or, if
-** there already exists a mapping for this file, and there are still
-** outstanding xFetch() references to it, this function is a no-op.
-**
-** If parameter nByte is non-negative, then it is the requested size of
-** the mapping to create. Otherwise, if nByte is less than zero, then the
-** requested size is the size of the file on disk. The actual size of the
-** created mapping is either the requested size or the value configured
-** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
-**
-** SQLITE_OK is returned if no error occurs (even if the mapping is not
-** recreated as a result of outstanding references) or an SQLite error
-** code otherwise.
-*/
-static int unixMapfile(unixFile *pFd, i64 nMap){
- assert( nMap>=0 || pFd->nFetchOut==0 );
- assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
- if( pFd->nFetchOut>0 ) return SQLITE_OK;
-
- if( nMap<0 ){
- struct stat statbuf; /* Low-level file information */
- if( osFstat(pFd->h, &statbuf) ){
- return SQLITE_IOERR_FSTAT;
- }
- nMap = statbuf.st_size;
- }
- if( nMap>pFd->mmapSizeMax ){
- nMap = pFd->mmapSizeMax;
- }
-
- assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
- if( nMap!=pFd->mmapSize ){
- unixRemapfile(pFd, nMap);
- }
-
- return SQLITE_OK;
-}
-#endif /* SQLITE_MAX_MMAP_SIZE>0 */
-
-/*
-** If possible, return a pointer to a mapping of file fd starting at offset
-** iOff. The mapping must be valid for at least nAmt bytes.
-**
-** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
-** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
-** Finally, if an error does occur, return an SQLite error code. The final
-** value of *pp is undefined in this case.
-**
-** If this function does return a pointer, the caller must eventually
-** release the reference by calling unixUnfetch().
-*/
-static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
-#if SQLITE_MAX_MMAP_SIZE>0
- unixFile *pFd = (unixFile *)fd; /* The underlying database file */
-#endif
- *pp = 0;
-
-#if SQLITE_MAX_MMAP_SIZE>0
- if( pFd->mmapSizeMax>0 ){
- if( pFd->pMapRegion==0 ){
- int rc = unixMapfile(pFd, -1);
- if( rc!=SQLITE_OK ) return rc;
- }
- if( pFd->mmapSize >= iOff+nAmt ){
- *pp = &((u8 *)pFd->pMapRegion)[iOff];
- pFd->nFetchOut++;
- }
- }
-#endif
- return SQLITE_OK;
-}
-
-/*
-** If the third argument is non-NULL, then this function releases a
-** reference obtained by an earlier call to unixFetch(). The second
-** argument passed to this function must be the same as the corresponding
-** argument that was passed to the unixFetch() invocation.
-**
-** Or, if the third argument is NULL, then this function is being called
-** to inform the VFS layer that, according to POSIX, any existing mapping
-** may now be invalid and should be unmapped.
-*/
-static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
-#if SQLITE_MAX_MMAP_SIZE>0
- unixFile *pFd = (unixFile *)fd; /* The underlying database file */
- UNUSED_PARAMETER(iOff);
-
- /* If p==0 (unmap the entire file) then there must be no outstanding
- ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
- ** then there must be at least one outstanding. */
- assert( (p==0)==(pFd->nFetchOut==0) );
-
- /* If p!=0, it must match the iOff value. */
- assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
-
- if( p ){
- pFd->nFetchOut--;
- }else{
- unixUnmapfile(pFd);
- }
-
- assert( pFd->nFetchOut>=0 );
-#else
- UNUSED_PARAMETER(fd);
- UNUSED_PARAMETER(p);
- UNUSED_PARAMETER(iOff);
-#endif
- return SQLITE_OK;
-}
-
-/*
-** Here ends the implementation of all sqlite3_file methods.
-**
-********************** End sqlite3_file Methods *******************************
-******************************************************************************/
-
-/*
-** This division contains definitions of sqlite3_io_methods objects that
-** implement various file locking strategies. It also contains definitions
-** of "finder" functions. A finder-function is used to locate the appropriate
-** sqlite3_io_methods object for a particular database file. The pAppData
-** field of the sqlite3_vfs VFS objects are initialized to be pointers to
-** the correct finder-function for that VFS.
-**
-** Most finder functions return a pointer to a fixed sqlite3_io_methods
-** object. The only interesting finder-function is autolockIoFinder, which
-** looks at the filesystem type and tries to guess the best locking
-** strategy from that.
-**
-** For finder-function F, two objects are created:
-**
-** (1) The real finder-function named "FImpt()".
-**
-** (2) A constant pointer to this function named just "F".
-**
-**
-** A pointer to the F pointer is used as the pAppData value for VFS
-** objects. We have to do this instead of letting pAppData point
-** directly at the finder-function since C90 rules prevent a void*
-** from be cast into a function pointer.
-**
-**
-** Each instance of this macro generates two objects:
-**
-** * A constant sqlite3_io_methods object call METHOD that has locking
-** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
-**
-** * An I/O method finder function called FINDER that returns a pointer
-** to the METHOD object in the previous bullet.
-*/
-#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
-static const sqlite3_io_methods METHOD = { \
- VERSION, /* iVersion */ \
- CLOSE, /* xClose */ \
- unixRead, /* xRead */ \
- unixWrite, /* xWrite */ \
- unixTruncate, /* xTruncate */ \
- unixSync, /* xSync */ \
- unixFileSize, /* xFileSize */ \
- LOCK, /* xLock */ \
- UNLOCK, /* xUnlock */ \
- CKLOCK, /* xCheckReservedLock */ \
- unixFileControl, /* xFileControl */ \
- unixSectorSize, /* xSectorSize */ \
- unixDeviceCharacteristics, /* xDeviceCapabilities */ \
- SHMMAP, /* xShmMap */ \
- unixShmLock, /* xShmLock */ \
- unixShmBarrier, /* xShmBarrier */ \
- unixShmUnmap, /* xShmUnmap */ \
- unixFetch, /* xFetch */ \
- unixUnfetch, /* xUnfetch */ \
-}; \
-static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
- UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
- return &METHOD; \
-} \
-static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
- = FINDER##Impl;
-
-/*
-** Here are all of the sqlite3_io_methods objects for each of the
-** locking strategies. Functions that return pointers to these methods
-** are also created.
-*/
-IOMETHODS(
- posixIoFinder, /* Finder function name */
- posixIoMethods, /* sqlite3_io_methods object name */
- 3, /* shared memory and mmap are enabled */
- unixClose, /* xClose method */
- unixLock, /* xLock method */
- unixUnlock, /* xUnlock method */
- unixCheckReservedLock, /* xCheckReservedLock method */
- unixShmMap /* xShmMap method */
-)
-IOMETHODS(
- nolockIoFinder, /* Finder function name */
- nolockIoMethods, /* sqlite3_io_methods object name */
- 3, /* shared memory and mmap are enabled */
- nolockClose, /* xClose method */
- nolockLock, /* xLock method */
- nolockUnlock, /* xUnlock method */
- nolockCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-IOMETHODS(
- dotlockIoFinder, /* Finder function name */
- dotlockIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- dotlockClose, /* xClose method */
- dotlockLock, /* xLock method */
- dotlockUnlock, /* xUnlock method */
- dotlockCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-
-#if SQLITE_ENABLE_LOCKING_STYLE
-IOMETHODS(
- flockIoFinder, /* Finder function name */
- flockIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- flockClose, /* xClose method */
- flockLock, /* xLock method */
- flockUnlock, /* xUnlock method */
- flockCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-#endif
-
-#if OS_VXWORKS
-IOMETHODS(
- semIoFinder, /* Finder function name */
- semIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- semXClose, /* xClose method */
- semXLock, /* xLock method */
- semXUnlock, /* xUnlock method */
- semXCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-#endif
-
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-IOMETHODS(
- afpIoFinder, /* Finder function name */
- afpIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- afpClose, /* xClose method */
- afpLock, /* xLock method */
- afpUnlock, /* xUnlock method */
- afpCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-#endif
-
-/*
-** The proxy locking method is a "super-method" in the sense that it
-** opens secondary file descriptors for the conch and lock files and
-** it uses proxy, dot-file, AFP, and flock() locking methods on those
-** secondary files. For this reason, the division that implements
-** proxy locking is located much further down in the file. But we need
-** to go ahead and define the sqlite3_io_methods and finder function
-** for proxy locking here. So we forward declare the I/O methods.
-*/
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-static int proxyClose(sqlite3_file*);
-static int proxyLock(sqlite3_file*, int);
-static int proxyUnlock(sqlite3_file*, int);
-static int proxyCheckReservedLock(sqlite3_file*, int*);
-IOMETHODS(
- proxyIoFinder, /* Finder function name */
- proxyIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- proxyClose, /* xClose method */
- proxyLock, /* xLock method */
- proxyUnlock, /* xUnlock method */
- proxyCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-#endif
-
-/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-IOMETHODS(
- nfsIoFinder, /* Finder function name */
- nfsIoMethods, /* sqlite3_io_methods object name */
- 1, /* shared memory is disabled */
- unixClose, /* xClose method */
- unixLock, /* xLock method */
- nfsUnlock, /* xUnlock method */
- unixCheckReservedLock, /* xCheckReservedLock method */
- 0 /* xShmMap method */
-)
-#endif
-
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-/*
-** This "finder" function attempts to determine the best locking strategy
-** for the database file "filePath". It then returns the sqlite3_io_methods
-** object that implements that strategy.
-**
-** This is for MacOSX only.
-*/
-static const sqlite3_io_methods *autolockIoFinderImpl(
- const char *filePath, /* name of the database file */
- unixFile *pNew /* open file object for the database file */
-){
- static const struct Mapping {
- const char *zFilesystem; /* Filesystem type name */
- const sqlite3_io_methods *pMethods; /* Appropriate locking method */
- } aMap[] = {
- { "hfs", &posixIoMethods },
- { "ufs", &posixIoMethods },
- { "afpfs", &afpIoMethods },
- { "smbfs", &afpIoMethods },
- { "webdav", &nolockIoMethods },
- { 0, 0 }
- };
- int i;
- struct statfs fsInfo;
- struct flock lockInfo;
-
- if( !filePath ){
- /* If filePath==NULL that means we are dealing with a transient file
- ** that does not need to be locked. */
- return &nolockIoMethods;
- }
- if( statfs(filePath, &fsInfo) != -1 ){
- if( fsInfo.f_flags & MNT_RDONLY ){
- return &nolockIoMethods;
- }
- for(i=0; aMap[i].zFilesystem; i++){
- if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
- return aMap[i].pMethods;
- }
- }
- }
-
- /* Default case. Handles, amongst others, "nfs".
- ** Test byte-range lock using fcntl(). If the call succeeds,
- ** assume that the file-system supports POSIX style locks.
- */
- lockInfo.l_len = 1;
- lockInfo.l_start = 0;
- lockInfo.l_whence = SEEK_SET;
- lockInfo.l_type = F_RDLCK;
- if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
- if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
- return &nfsIoMethods;
- } else {
- return &posixIoMethods;
- }
- }else{
- return &dotlockIoMethods;
- }
-}
-static const sqlite3_io_methods
- *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
-
-#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
-
-#if OS_VXWORKS
-/*
-** This "finder" function for VxWorks checks to see if posix advisory
-** locking works. If it does, then that is what is used. If it does not
-** work, then fallback to named semaphore locking.
-*/
-static const sqlite3_io_methods *vxworksIoFinderImpl(
- const char *filePath, /* name of the database file */
- unixFile *pNew /* the open file object */
-){
- struct flock lockInfo;
-
- if( !filePath ){
- /* If filePath==NULL that means we are dealing with a transient file
- ** that does not need to be locked. */
- return &nolockIoMethods;
- }
-
- /* Test if fcntl() is supported and use POSIX style locks.
- ** Otherwise fall back to the named semaphore method.
- */
- lockInfo.l_len = 1;
- lockInfo.l_start = 0;
- lockInfo.l_whence = SEEK_SET;
- lockInfo.l_type = F_RDLCK;
- if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
- return &posixIoMethods;
- }else{
- return &semIoMethods;
- }
-}
-static const sqlite3_io_methods
- *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
-
-#endif /* OS_VXWORKS */
-
-/*
-** An abstract type for a pointer to an IO method finder function:
-*/
-typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
-
-
-/****************************************************************************
-**************************** sqlite3_vfs methods ****************************
-**
-** This division contains the implementation of methods on the
-** sqlite3_vfs object.
-*/
-
-/*
-** Initialize the contents of the unixFile structure pointed to by pId.
-*/
-static int fillInUnixFile(
- sqlite3_vfs *pVfs, /* Pointer to vfs object */
- int h, /* Open file descriptor of file being opened */
- sqlite3_file *pId, /* Write to the unixFile structure here */
- const char *zFilename, /* Name of the file being opened */
- int ctrlFlags /* Zero or more UNIXFILE_* values */
-){
- const sqlite3_io_methods *pLockingStyle;
- unixFile *pNew = (unixFile *)pId;
- int rc = SQLITE_OK;
-
- assert( pNew->pInode==NULL );
-
- /* No locking occurs in temporary files */
- assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
-
- OSTRACE(("OPEN %-3d %s\n", h, zFilename));
- pNew->h = h;
- pNew->pVfs = pVfs;
- pNew->zPath = zFilename;
- pNew->ctrlFlags = (u8)ctrlFlags;
-#if SQLITE_MAX_MMAP_SIZE>0
- pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
-#endif
- if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
- "psow", SQLITE_POWERSAFE_OVERWRITE) ){
- pNew->ctrlFlags |= UNIXFILE_PSOW;
- }
- if( strcmp(pVfs->zName,"unix-excl")==0 ){
- pNew->ctrlFlags |= UNIXFILE_EXCL;
- }
-
-#if OS_VXWORKS
- pNew->pId = vxworksFindFileId(zFilename);
- if( pNew->pId==0 ){
- ctrlFlags |= UNIXFILE_NOLOCK;
- rc = SQLITE_NOMEM_BKPT;
- }
-#endif
-
- if( ctrlFlags & UNIXFILE_NOLOCK ){
- pLockingStyle = &nolockIoMethods;
- }else{
- pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
-#if SQLITE_ENABLE_LOCKING_STYLE
- /* Cache zFilename in the locking context (AFP and dotlock override) for
- ** proxyLock activation is possible (remote proxy is based on db name)
- ** zFilename remains valid until file is closed, to support */
- pNew->lockingContext = (void*)zFilename;
-#endif
- }
-
- if( pLockingStyle == &posixIoMethods
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
- || pLockingStyle == &nfsIoMethods
-#endif
- ){
- unixEnterMutex();
- rc = findInodeInfo(pNew, &pNew->pInode);
- if( rc!=SQLITE_OK ){
- /* If an error occurred in findInodeInfo(), close the file descriptor
- ** immediately, before releasing the mutex. findInodeInfo() may fail
- ** in two scenarios:
- **
- ** (a) A call to fstat() failed.
- ** (b) A malloc failed.
- **
- ** Scenario (b) may only occur if the process is holding no other
- ** file descriptors open on the same file. If there were other file
- ** descriptors on this file, then no malloc would be required by
- ** findInodeInfo(). If this is the case, it is quite safe to close
- ** handle h - as it is guaranteed that no posix locks will be released
- ** by doing so.
- **
- ** If scenario (a) caused the error then things are not so safe. The
- ** implicit assumption here is that if fstat() fails, things are in
- ** such bad shape that dropping a lock or two doesn't matter much.
- */
- robust_close(pNew, h, __LINE__);
- h = -1;
- }
- unixLeaveMutex();
- }
-
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
- else if( pLockingStyle == &afpIoMethods ){
- /* AFP locking uses the file path so it needs to be included in
- ** the afpLockingContext.
- */
- afpLockingContext *pCtx;
- pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
- if( pCtx==0 ){
- rc = SQLITE_NOMEM_BKPT;
- }else{
- /* NB: zFilename exists and remains valid until the file is closed
- ** according to requirement F11141. So we do not need to make a
- ** copy of the filename. */
- pCtx->dbPath = zFilename;
- pCtx->reserved = 0;
- srandomdev();
- unixEnterMutex();
- rc = findInodeInfo(pNew, &pNew->pInode);
- if( rc!=SQLITE_OK ){
- sqlite3_free(pNew->lockingContext);
- robust_close(pNew, h, __LINE__);
- h = -1;
- }
- unixLeaveMutex();
- }
- }
-#endif
-
- else if( pLockingStyle == &dotlockIoMethods ){
- /* Dotfile locking uses the file path so it needs to be included in
- ** the dotlockLockingContext
- */
- char *zLockFile;
- int nFilename;
- assert( zFilename!=0 );
- nFilename = (int)strlen(zFilename) + 6;
- zLockFile = (char *)sqlite3_malloc64(nFilename);
- if( zLockFile==0 ){
- rc = SQLITE_NOMEM_BKPT;
- }else{
- sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
- }
- pNew->lockingContext = zLockFile;
- }
-
-#if OS_VXWORKS
- else if( pLockingStyle == &semIoMethods ){
- /* Named semaphore locking uses the file path so it needs to be
- ** included in the semLockingContext
- */
- unixEnterMutex();
- rc = findInodeInfo(pNew, &pNew->pInode);
- if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
- char *zSemName = pNew->pInode->aSemName;
- int n;
- sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
- pNew->pId->zCanonicalName);
- for( n=1; zSemName[n]; n++ )
- if( zSemName[n]=='/' ) zSemName[n] = '_';
- pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
- if( pNew->pInode->pSem == SEM_FAILED ){
- rc = SQLITE_NOMEM_BKPT;
- pNew->pInode->aSemName[0] = '\0';
- }
- }
- unixLeaveMutex();
- }
-#endif
-
- storeLastErrno(pNew, 0);
-#if OS_VXWORKS
- if( rc!=SQLITE_OK ){
- if( h>=0 ) robust_close(pNew, h, __LINE__);
- h = -1;
- osUnlink(zFilename);
- pNew->ctrlFlags |= UNIXFILE_DELETE;
- }
-#endif
- if( rc!=SQLITE_OK ){
- if( h>=0 ) robust_close(pNew, h, __LINE__);
- }else{
- pNew->pMethod = pLockingStyle;
- OpenCounter(+1);
- verifyDbFile(pNew);
- }
- return rc;
-}
-
-/*
-** Return the name of a directory in which to put temporary files.
-** If no suitable temporary file directory can be found, return NULL.
-*/
-static const char *unixTempFileDir(void){
- static const char *azDirs[] = {
- 0,
- 0,
- "/var/tmp",
- "/usr/tmp",
- "/tmp",
- "."
- };
- unsigned int i = 0;
- struct stat buf;
- const char *zDir = sqlite3_temp_directory;
-
- if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
- if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
- while(1){
- if( zDir!=0
- && osStat(zDir, &buf)==0
- && S_ISDIR(buf.st_mode)
- && osAccess(zDir, 03)==0
- ){
- return zDir;
- }
- if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
- zDir = azDirs[i++];
- }
- return 0;
-}
-
-/*
-** Create a temporary file name in zBuf. zBuf must be allocated
-** by the calling process and must be big enough to hold at least
-** pVfs->mxPathname bytes.
-*/
-static int unixGetTempname(int nBuf, char *zBuf){
- const char *zDir;
- int iLimit = 0;
-
- /* 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.
- */
- zBuf[0] = 0;
- SimulateIOError( return SQLITE_IOERR );
-
- zDir = unixTempFileDir();
- if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
- do{
- u64 r;
- sqlite3_randomness(sizeof(r), &r);
- assert( nBuf>2 );
- zBuf[nBuf-2] = 0;
- sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
- zDir, r, 0);
- if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
- }while( osAccess(zBuf,0)==0 );
- return SQLITE_OK;
-}
-
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
-/*
-** Routine to transform a unixFile into a proxy-locking unixFile.
-** Implementation in the proxy-lock division, but used by unixOpen()
-** if SQLITE_PREFER_PROXY_LOCKING is defined.
-*/
-static int proxyTransformUnixFile(unixFile*, const char*);
-#endif
-
-/*
-** Search for an unused file descriptor that was opened on the database
-** file (not a journal or master-journal file) identified by pathname
-** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
-** argument to this function.
-**
-** Such a file descriptor may exist if a database connection was closed
-** but the associated file descriptor could not be closed because some
-** other file descriptor open on the same file is holding a file-lock.
-** Refer to comments in the unixClose() function and the lengthy comment
-** describing "Posix Advisory Locking" at the start of this file for
-** further details. Also, ticket #4018.
-**
-** If a suitable file descriptor is found, then it is returned. If no
-** such file descriptor is located, -1 is returned.
-*/
-static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
- UnixUnusedFd *pUnused = 0;
-
- /* Do not search for an unused file descriptor on vxworks. Not because
- ** vxworks would not benefit from the change (it might, we're not sure),
- ** but because no way to test it is currently available. It is better
- ** not to risk breaking vxworks support for the sake of such an obscure
- ** feature. */
-#if !OS_VXWORKS
- struct stat sStat; /* Results of stat() call */
-
- unixEnterMutex();
-
- /* A stat() call may fail for various reasons. If this happens, it is
- ** almost certain that an open() call on the same path will also fail.
- ** For this reason, if an error occurs in the stat() call here, it is
- ** ignored and -1 is returned. The caller will try to open a new file
- ** descriptor on the same path, fail, and return an error to SQLite.
- **
- ** Even if a subsequent open() call does succeed, the consequences of
- ** not searching for a reusable file descriptor are not dire. */
- if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
- unixInodeInfo *pInode;
-
- pInode = inodeList;
- while( pInode && (pInode->fileId.dev!=sStat.st_dev
- || pInode->fileId.ino!=(u64)sStat.st_ino) ){
- pInode = pInode->pNext;
- }
- if( pInode ){
- UnixUnusedFd **pp;
- assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
- sqlite3_mutex_enter(pInode->pLockMutex);
- for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
- pUnused = *pp;
- if( pUnused ){
- *pp = pUnused->pNext;
- }
- sqlite3_mutex_leave(pInode->pLockMutex);
- }
- }
- unixLeaveMutex();
-#endif /* if !OS_VXWORKS */
- return pUnused;
-}
-
-/*
-** Find the mode, uid and gid of file zFile.
-*/
-static int getFileMode(
- const char *zFile, /* File name */
- mode_t *pMode, /* OUT: Permissions of zFile */
- uid_t *pUid, /* OUT: uid of zFile. */
- gid_t *pGid /* OUT: gid of zFile. */
-){
- struct stat sStat; /* Output of stat() on database file */
- int rc = SQLITE_OK;
- if( 0==osStat(zFile, &sStat) ){
- *pMode = sStat.st_mode & 0777;
- *pUid = sStat.st_uid;
- *pGid = sStat.st_gid;
- }else{
- rc = SQLITE_IOERR_FSTAT;
- }
- return rc;
-}
-
-/*
-** This function is called by unixOpen() to determine the unix permissions
-** to create new files with. If no error occurs, then SQLITE_OK is returned
-** and a value suitable for passing as the third argument to open(2) is
-** written to *pMode. If an IO error occurs, an SQLite error code is
-** returned and the value of *pMode is not modified.
-**
-** In most cases, this routine sets *pMode to 0, which will become
-** an indication to robust_open() to create the file using
-** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
-** But if the file being opened is a WAL or regular journal file, then
-** this function queries the file-system for the permissions on the
-** corresponding database file and sets *pMode to this value. Whenever
-** possible, WAL and journal files are created using the same permissions
-** as the associated database file.
-**
-** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
-** original filename is unavailable. But 8_3_NAMES is only used for
-** FAT filesystems and permissions do not matter there, so just use
-** the default permissions.
-*/
-static int findCreateFileMode(
- const char *zPath, /* Path of file (possibly) being created */
- int flags, /* Flags passed as 4th argument to xOpen() */
- mode_t *pMode, /* OUT: Permissions to open file with */
- uid_t *pUid, /* OUT: uid to set on the file */
- gid_t *pGid /* OUT: gid to set on the file */
-){
- int rc = SQLITE_OK; /* Return Code */
- *pMode = 0;
- *pUid = 0;
- *pGid = 0;
- if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
- char zDb[MAX_PATHNAME+1]; /* Database file path */
- int nDb; /* Number of valid bytes in zDb */
-
- /* zPath is a path to a WAL or journal file. The following block derives
- ** the path to the associated database file from zPath. This block handles
- ** the following naming conventions:
- **
- ** "-journal"
- ** "-wal"
- ** "-journalNN"
- ** "-walNN"
- **
- ** where NN is a decimal number. The NN naming schemes are
- ** used by the test_multiplex.c module.
- */
- nDb = sqlite3Strlen30(zPath) - 1;
- while( zPath[nDb]!='-' ){
- /* In normal operation, the journal file name will always contain
- ** a '-' character. However in 8+3 filename mode, or if a corrupt
- ** rollback journal specifies a master journal with a goofy name, then
- ** the '-' might be missing. */
- if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
- nDb--;
- }
- memcpy(zDb, zPath, nDb);
- zDb[nDb] = '\0';
-
- rc = getFileMode(zDb, pMode, pUid, pGid);
- }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
- *pMode = 0600;
- }else if( flags & SQLITE_OPEN_URI ){
- /* If this is a main database file and the file was opened using a URI
- ** filename, check for the "modeof" parameter. If present, interpret
- ** its value as a filename and try to copy the mode, uid and gid from
- ** that file. */
- const char *z = sqlite3_uri_parameter(zPath, "modeof");
- if( z ){
- rc = getFileMode(z, pMode, pUid, pGid);
- }
- }
- return rc;
-}
-
-/*
-** Open the file zPath.
-**
-** Previously, the SQLite OS layer used three functions in place of this
-** one:
-**
-** sqlite3OsOpenReadWrite();
-** sqlite3OsOpenReadOnly();
-** sqlite3OsOpenExclusive();
-**
-** These calls correspond to the following combinations of flags:
-**
-** ReadWrite() -> (READWRITE | CREATE)
-** ReadOnly() -> (READONLY)
-** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
-**
-** The old OpenExclusive() accepted a boolean argument - "delFlag". If
-** true, the file was configured to be automatically deleted when the
-** file handle closed. To achieve the same effect using this new
-** interface, add the DELETEONCLOSE flag to those specified above for
-** OpenExclusive().
-*/
-static int unixOpen(
- sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
- const char *zPath, /* Pathname of file to be opened */
- sqlite3_file *pFile, /* The file descriptor to be filled in */
- int flags, /* Input flags to control the opening */
- int *pOutFlags /* Output flags returned to SQLite core */
-){
- unixFile *p = (unixFile *)pFile;
- int fd = -1; /* File descriptor returned by open() */
- int openFlags = 0; /* Flags to pass to open() */
- int eType = flags&0xFFFFFF00; /* Type of file to open */
- int noLock; /* True to omit locking primitives */
- int rc = SQLITE_OK; /* Function Return Code */
- int ctrlFlags = 0; /* UNIXFILE_* flags */
-
- int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
- int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
- int isCreate = (flags & SQLITE_OPEN_CREATE);
- int isReadonly = (flags & SQLITE_OPEN_READONLY);
- int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
-#if SQLITE_ENABLE_LOCKING_STYLE
- int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
-#endif
-#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
- struct statfs fsInfo;
-#endif
-
- /* If creating a master or main-file journal, this function will open
- ** a file-descriptor on the directory too. The first time unixSync()
- ** is called the directory file descriptor will be fsync()ed and close()d.
- */
- int isNewJrnl = (isCreate && (
- eType==SQLITE_OPEN_MASTER_JOURNAL
- || eType==SQLITE_OPEN_MAIN_JOURNAL
- || eType==SQLITE_OPEN_WAL
- ));
-
- /* 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.
- */
- char zTmpname[MAX_PATHNAME+2];
- const char *zName = zPath;
-
- /* 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.
- */
- assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
- assert(isCreate==0 || isReadWrite);
- assert(isExclusive==0 || isCreate);
- assert(isDelete==0 || isCreate);
-
- /* The main DB, main journal, WAL file and master journal are never
- ** automatically deleted. Nor are they ever temporary files. */
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
-
- /* Assert that the upper layer has set one of the "file-type" flags. */
- 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
- );
-
- /* Detect a pid change and reset the PRNG. There is a race condition
- ** here such that two or more threads all trying to open databases at
- ** the same instant might all reset the PRNG. But multiple resets
- ** are harmless.
- */
- if( randomnessPid!=osGetpid(0) ){
- randomnessPid = osGetpid(0);
- sqlite3_randomness(0,0);
- }
- memset(p, 0, sizeof(unixFile));
-
- if( eType==SQLITE_OPEN_MAIN_DB ){
- UnixUnusedFd *pUnused;
- pUnused = findReusableFd(zName, flags);
- if( pUnused ){
- fd = pUnused->fd;
- }else{
- pUnused = sqlite3_malloc64(sizeof(*pUnused));
- if( !pUnused ){
- return SQLITE_NOMEM_BKPT;
- }
- }
- p->pPreallocatedUnused = pUnused;
-
- /* Database filenames are double-zero terminated if they are not
- ** URIs with parameters. Hence, they can always be passed into
- ** sqlite3_uri_parameter(). */
- assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
-
- }else if( !zName ){
- /* If zName is NULL, the upper layer is requesting a temp file. */
- assert(isDelete && !isNewJrnl);
- rc = unixGetTempname(pVfs->mxPathname, zTmpname);
- if( rc!=SQLITE_OK ){
- return rc;
- }
- zName = zTmpname;
-
- /* Generated temporary filenames are always double-zero terminated
- ** for use by sqlite3_uri_parameter(). */
- assert( zName[strlen(zName)+1]==0 );
- }
-
- /* Determine the value of the flags parameter passed to POSIX function
- ** open(). These must be calculated even if open() is not called, as
- ** they may be stored as part of the file handle and used by the
- ** 'conch file' locking functions later on. */
- if( isReadonly ) openFlags |= O_RDONLY;
- if( isReadWrite ) openFlags |= O_RDWR;
- if( isCreate ) openFlags |= O_CREAT;
- if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
- openFlags |= (O_LARGEFILE|O_BINARY);
-
- if( fd<0 ){
- mode_t openMode; /* Permissions to create file with */
- uid_t uid; /* Userid for the file */
- gid_t gid; /* Groupid for the file */
- rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
- if( rc!=SQLITE_OK ){
- assert( !p->pPreallocatedUnused );
- assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
- return rc;
- }
- fd = robust_open(zName, openFlags, openMode);
- OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
- assert( !isExclusive || (openFlags & O_CREAT)!=0 );
- if( fd<0 ){
- if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
- /* If unable to create a journal because the directory is not
- ** writable, change the error code to indicate that. */
- rc = SQLITE_READONLY_DIRECTORY;
- }else if( errno!=EISDIR && isReadWrite ){
- /* Failed to open the file for read/write access. Try read-only. */
- flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
- openFlags &= ~(O_RDWR|O_CREAT);
- flags |= SQLITE_OPEN_READONLY;
- openFlags |= O_RDONLY;
- isReadonly = 1;
- fd = robust_open(zName, openFlags, openMode);
- }
- }
- if( fd<0 ){
- int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
- if( rc==SQLITE_OK ) rc = rc2;
- goto open_finished;
- }
-
- /* If this process is running as root and if creating a new rollback
- ** journal or WAL file, set the ownership of the journal or WAL to be
- ** the same as the original database.
- */
- if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
- robustFchown(fd, uid, gid);
- }
- }
- assert( fd>=0 );
- if( pOutFlags ){
- *pOutFlags = flags;
- }
-
- if( p->pPreallocatedUnused ){
- p->pPreallocatedUnused->fd = fd;
- p->pPreallocatedUnused->flags = flags;
- }
-
- if( isDelete ){
-#if OS_VXWORKS
- zPath = zName;
-#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
- zPath = sqlite3_mprintf("%s", zName);
- if( zPath==0 ){
- robust_close(p, fd, __LINE__);
- return SQLITE_NOMEM_BKPT;
- }
-#else
- osUnlink(zName);
-#endif
- }
-#if SQLITE_ENABLE_LOCKING_STYLE
- else{
- p->openFlags = openFlags;
- }
-#endif
-
-#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
- if( fstatfs(fd, &fsInfo) == -1 ){
- storeLastErrno(p, errno);
- robust_close(p, fd, __LINE__);
- return SQLITE_IOERR_ACCESS;
- }
- if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
- ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
- }
- if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
- ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
- }
-#endif
-
- /* Set up appropriate ctrlFlags */
- if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
- if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
- noLock = eType!=SQLITE_OPEN_MAIN_DB;
- if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
- if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
- if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
-
-#if SQLITE_ENABLE_LOCKING_STYLE
-#if SQLITE_PREFER_PROXY_LOCKING
- isAutoProxy = 1;
-#endif
- if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
- char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
- int useProxy = 0;
-
- /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
- ** never use proxy, NULL means use proxy for non-local files only. */
- if( envforce!=NULL ){
- useProxy = atoi(envforce)>0;
- }else{
- useProxy = !(fsInfo.f_flags&MNT_LOCAL);
- }
- if( useProxy ){
- rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
- if( rc==SQLITE_OK ){
- rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
- if( rc!=SQLITE_OK ){
- /* Use unixClose to clean up the resources added in fillInUnixFile
- ** and clear all the structure's references. Specifically,
- ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
- */
- unixClose(pFile);
- return rc;
- }
- }
- goto open_finished;
- }
- }
-#endif
-
- assert( zPath==0 || zPath[0]=='/'
- || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
- );
- rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
-
-open_finished:
- if( rc!=SQLITE_OK ){
- sqlite3_free(p->pPreallocatedUnused);
- }
- return rc;
-}
-
-
-/*
-** Delete the file at zPath. If the dirSync argument is true, fsync()
-** the directory after deleting the file.
-*/
-static int unixDelete(
- sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
- const char *zPath, /* Name of file to be deleted */
- int dirSync /* If true, fsync() directory after deleting file */
-){
- int rc = SQLITE_OK;
- UNUSED_PARAMETER(NotUsed);
- SimulateIOError(return SQLITE_IOERR_DELETE);
- if( osUnlink(zPath)==(-1) ){
- if( errno==ENOENT
-#if OS_VXWORKS
- || osAccess(zPath,0)!=0
-#endif
- ){
- rc = SQLITE_IOERR_DELETE_NOENT;
- }else{
- rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
- }
- return rc;
- }
-#ifndef SQLITE_DISABLE_DIRSYNC
- if( (dirSync & 1)!=0 ){
- int fd;
- rc = osOpenDirectory(zPath, &fd);
- if( rc==SQLITE_OK ){
- if( full_fsync(fd,0,0) ){
- rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
- }
- robust_close(0, fd, __LINE__);
- }else{
- assert( rc==SQLITE_CANTOPEN );
- rc = SQLITE_OK;
- }
- }
-#endif
- return rc;
-}
-
-/*
-** Test the existence of or access permissions of file zPath. The
-** test performed depends on the value of flags:
-**
-** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
-** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
-** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
-**
-** Otherwise return 0.
-*/
-static int unixAccess(
- sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
- const char *zPath, /* Path of the file to examine */
- int flags, /* What do we want to learn about the zPath file? */
- int *pResOut /* Write result boolean here */
-){
- UNUSED_PARAMETER(NotUsed);
- SimulateIOError( return SQLITE_IOERR_ACCESS; );
- assert( pResOut!=0 );
-
- /* The spec says there are three possible values for flags. But only
- ** two of them are actually used */
- assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
-
- if( flags==SQLITE_ACCESS_EXISTS ){
- struct stat buf;
- *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
- }else{
- *pResOut = osAccess(zPath, W_OK|R_OK)==0;
- }
- return SQLITE_OK;
-}
-
-/*
-**
-*/
-static int mkFullPathname(
- const char *zPath, /* Input path */
- char *zOut, /* Output buffer */
- int nOut /* Allocated size of buffer zOut */
-){
- int nPath = sqlite3Strlen30(zPath);
- int iOff = 0;
- if( zPath[0]!='/' ){
- if( osGetcwd(zOut, nOut-2)==0 ){
- return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
- }
- iOff = sqlite3Strlen30(zOut);
- zOut[iOff++] = '/';
- }
- if( (iOff+nPath+1)>nOut ){
- /* SQLite assumes that xFullPathname() nul-terminates the output buffer
- ** even if it returns an error. */
- zOut[iOff] = '\0';
- return SQLITE_CANTOPEN_BKPT;
- }
- sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
- return SQLITE_OK;
-}
-
-/*
-** Turn a relative pathname into a full pathname. The relative path
-** is stored as a nul-terminated string in the buffer pointed to by
-** zPath.
-**
-** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
-** (in this case, MAX_PATHNAME bytes). The full-path is written to
-** this buffer before returning.
-*/
-static int unixFullPathname(
- sqlite3_vfs *pVfs, /* Pointer to vfs object */
- const char *zPath, /* Possibly relative input path */
- int nOut, /* Size of output buffer in bytes */
- char *zOut /* Output buffer */
-){
-#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
- return mkFullPathname(zPath, zOut, nOut);
-#else
- int rc = SQLITE_OK;
- int nByte;
- int nLink = 1; /* Number of symbolic links followed so far */
- const char *zIn = zPath; /* Input path for each iteration of loop */
- char *zDel = 0;
-
- assert( pVfs->mxPathname==MAX_PATHNAME );
- UNUSED_PARAMETER(pVfs);
-
- /* 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.
- */
- SimulateIOError( return SQLITE_ERROR );
-
- do {
-
- /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
- ** link, or false otherwise. */
- int bLink = 0;
- struct stat buf;
- if( osLstat(zIn, &buf)!=0 ){
- if( errno!=ENOENT ){
- rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
- }
- }else{
- bLink = S_ISLNK(buf.st_mode);
- }
-
- if( bLink ){
- if( zDel==0 ){
- zDel = sqlite3_malloc(nOut);
- if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
- }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
- rc = SQLITE_CANTOPEN_BKPT;
- }
-
- if( rc==SQLITE_OK ){
- nByte = osReadlink(zIn, zDel, nOut-1);
- if( nByte<0 ){
- rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
- }else{
- if( zDel[0]!='/' ){
- int n;
- for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
- if( nByte+n+1>nOut ){
- rc = SQLITE_CANTOPEN_BKPT;
- }else{
- memmove(&zDel[n], zDel, nByte+1);
- memcpy(zDel, zIn, n);
- nByte += n;
- }
- }
- zDel[nByte] = '\0';
- }
- }
-
- zIn = zDel;
- }
-
- assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
- if( rc==SQLITE_OK && zIn!=zOut ){
- rc = mkFullPathname(zIn, zOut, nOut);
- }
- if( bLink==0 ) break;
- zIn = zOut;
- }while( rc==SQLITE_OK );
-
- sqlite3_free(zDel);
- return rc;
-#endif /* HAVE_READLINK && HAVE_LSTAT */
-}
-
-
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-/*
-** Interfaces for opening a shared library, finding entry points
-** within the shared library, and closing the shared library.
-*/
-#include
-static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
- UNUSED_PARAMETER(NotUsed);
- return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
-}
-
-/*
-** SQLite calls this function immediately after a call to unixDlSym() or
-** unixDlOpen() fails (returns a null pointer). If a more detailed error
-** message is available, it is written to zBufOut. If no error message
-** is available, zBufOut is left unmodified and SQLite uses a default
-** error message.
-*/
-static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
- const char *zErr;
- UNUSED_PARAMETER(NotUsed);
- unixEnterMutex();
- zErr = dlerror();
- if( zErr ){
- sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
- }
- unixLeaveMutex();
-}
-static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
- /*
- ** GCC with -pedantic-errors says that C90 does not allow a void* to be
- ** cast into a pointer to a function. And yet the library dlsym() routine
- ** returns a void* which is really a pointer to a function. So how do we
- ** use dlsym() with -pedantic-errors?
- **
- ** Variable x below is defined to be a pointer to a function taking
- ** parameters void* and const char* and returning a pointer to a function.
- ** We initialize x by assigning it a pointer to the dlsym() function.
- ** (That assignment requires a cast.) Then we call the function that
- ** x points to.
- **
- ** This work-around is unlikely to work correctly on any system where
- ** you really cannot cast a function pointer into void*. But then, on the
- ** other hand, dlsym() will not work on such a system either, so we have
- ** not really lost anything.
- */
- void (*(*x)(void*,const char*))(void);
- UNUSED_PARAMETER(NotUsed);
- x = (void(*(*)(void*,const char*))(void))dlsym;
- return (*x)(p, zSym);
-}
-static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
- UNUSED_PARAMETER(NotUsed);
- dlclose(pHandle);
-}
-#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
- #define unixDlOpen 0
- #define unixDlError 0
- #define unixDlSym 0
- #define unixDlClose 0
-#endif
-
-/*
-** Write nBuf bytes of random data to the supplied buffer zBuf.
-*/
-static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
- UNUSED_PARAMETER(NotUsed);
- assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
-
- /* We have to initialize zBuf to prevent valgrind from reporting
- ** errors. The reports issued by valgrind are incorrect - we would
- ** prefer that the randomness be increased by making use of the
- ** uninitialized space in zBuf - but valgrind errors tend to worry
- ** some users. Rather than argue, it seems easier just to initialize
- ** the whole array and silence valgrind, even if that means less randomness
- ** in the random seed.
- **
- ** When testing, initializing zBuf[] to zero is all we do. That means
- ** that we always use the same random number sequence. This makes the
- ** tests repeatable.
- */
- memset(zBuf, 0, nBuf);
- randomnessPid = osGetpid(0);
-#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
- {
- int fd, got;
- fd = robust_open("/dev/urandom", O_RDONLY, 0);
- if( fd<0 ){
- time_t t;
- time(&t);
- memcpy(zBuf, &t, sizeof(t));
- memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
- assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
- nBuf = sizeof(t) + sizeof(randomnessPid);
- }else{
- do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
- robust_close(0, fd, __LINE__);
- }
- }
-#endif
- return nBuf;
-}
-
-
-/*
-** Sleep for a little while. Return the amount of time slept.
-** The argument is the number of microseconds we want to sleep.
-** The return value is the number of microseconds of sleep actually
-** requested from the underlying operating system, a number which
-** might be greater than or equal to the argument, but not less
-** than the argument.
-*/
-static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
-#if OS_VXWORKS
- struct timespec sp;
-
- sp.tv_sec = microseconds / 1000000;
- sp.tv_nsec = (microseconds % 1000000) * 1000;
- nanosleep(&sp, NULL);
- UNUSED_PARAMETER(NotUsed);
- return microseconds;
-#elif defined(HAVE_USLEEP) && HAVE_USLEEP
- usleep(microseconds);
- UNUSED_PARAMETER(NotUsed);
- return microseconds;
-#else
- int seconds = (microseconds+999999)/1000000;
- sleep(seconds);
- UNUSED_PARAMETER(NotUsed);
- return seconds*1000000;
-#endif
-}
-
-/*
-** 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.
-*/
-#ifdef SQLITE_TEST
-SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
-#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 SQLITE_OK. Return SQLITE_ERROR if the time and date
-** cannot be found.
-*/
-static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
- static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
- int rc = SQLITE_OK;
-#if defined(NO_GETTOD)
- time_t t;
- time(&t);
- *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
-#elif OS_VXWORKS
- struct timespec sNow;
- clock_gettime(CLOCK_REALTIME, &sNow);
- *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
-#else
- struct timeval sNow;
- (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
- *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
-#endif
-
-#ifdef SQLITE_TEST
- if( sqlite3_current_time ){
- *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
- }
-#endif
- UNUSED_PARAMETER(NotUsed);
- return rc;
-}
-
-#ifndef SQLITE_OMIT_DEPRECATED
-/*
-** 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 unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
- sqlite3_int64 i = 0;
- int rc;
- UNUSED_PARAMETER(NotUsed);
- rc = unixCurrentTimeInt64(0, &i);
- *prNow = i/86400000.0;
- return rc;
-}
-#else
-# define unixCurrentTime 0
-#endif
-
-/*
-** The xGetLastError() method is designed to return a better
-** low-level error message when operating-system problems come up
-** during SQLite operation. Only the integer return code is currently
-** used.
-*/
-static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
- UNUSED_PARAMETER(NotUsed);
- UNUSED_PARAMETER(NotUsed2);
- UNUSED_PARAMETER(NotUsed3);
- return errno;
-}
-
-
-/*
-************************ End of sqlite3_vfs methods ***************************
-******************************************************************************/
-
-/******************************************************************************
-************************** Begin Proxy Locking ********************************
-**
-** Proxy locking is a "uber-locking-method" in this sense: It uses the
-** other locking methods on secondary lock files. Proxy locking is a
-** meta-layer over top of the primitive locking implemented above. For
-** this reason, the division that implements of proxy locking is deferred
-** until late in the file (here) after all of the other I/O methods have
-** been defined - so that the primitive locking methods are available
-** as services to help with the implementation of proxy locking.
-**
-****
-**
-** The default locking schemes in SQLite use byte-range locks on the
-** database file to coordinate safe, concurrent access by multiple readers
-** and writers [http://sqlite.org/lockingv3.html]. The five file locking
-** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
-** as POSIX read & write locks over fixed set of locations (via fsctl),
-** on AFP and SMB only exclusive byte-range locks are available via fsctl
-** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
-** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
-** address in the shared range is taken for a SHARED lock, the entire
-** shared range is taken for an EXCLUSIVE lock):
-**
-** PENDING_BYTE 0x40000000
-** RESERVED_BYTE 0x40000001
-** SHARED_RANGE 0x40000002 -> 0x40000200
-**
-** This works well on the local file system, but shows a nearly 100x
-** slowdown in read performance on AFP because the AFP client disables
-** the read cache when byte-range locks are present. Enabling the read
-** cache exposes a cache coherency problem that is present on all OS X
-** supported network file systems. NFS and AFP both observe the
-** close-to-open semantics for ensuring cache coherency
-** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
-** address the requirements for concurrent database access by multiple
-** readers and writers
-** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
-**
-** To address the performance and cache coherency issues, proxy file locking
-** changes the way database access is controlled by limiting access to a
-** single host at a time and moving file locks off of the database file
-** and onto a proxy file on the local file system.
-**
-**
-** Using proxy locks
-** -----------------
-**
-** C APIs
-**
-** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
-** | ":auto:");
-** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
-** &);
-**
-**
-** SQL pragmas
-**
-** PRAGMA [database.]lock_proxy_file= | :auto:
-** PRAGMA [database.]lock_proxy_file
-**
-** Specifying ":auto:" means that if there is a conch file with a matching
-** host ID in it, the proxy path in the conch file will be used, otherwise
-** a proxy path based on the user's temp dir
-** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
-** actual proxy file name is generated from the name and path of the
-** database file. For example:
-**
-** For database path "/Users/me/foo.db"
-** The lock path will be "/sqliteplocks/_Users_me_foo.db:auto:")
-**
-** Once a lock proxy is configured for a database connection, it can not
-** be removed, however it may be switched to a different proxy path via
-** the above APIs (assuming the conch file is not being held by another
-** connection or process).
-**
-**
-** How proxy locking works
-** -----------------------
-**
-** Proxy file locking relies primarily on two new supporting files:
-**
-** * conch file to limit access to the database file to a single host
-** at a time
-**
-** * proxy file to act as a proxy for the advisory locks normally
-** taken on the database
-**
-** The conch file - to use a proxy file, sqlite must first "hold the conch"
-** by taking an sqlite-style shared lock on the conch file, reading the
-** contents and comparing the host's unique host ID (see below) and lock
-** proxy path against the values stored in the conch. The conch file is
-** stored in the same directory as the database file and the file name
-** is patterned after the database file name as ".-conch".
-** If the conch file does not exist, or its contents do not match the
-** host ID and/or proxy path, then the lock is escalated to an exclusive
-** lock and the conch file contents is updated with the host ID and proxy
-** path and the lock is downgraded to a shared lock again. If the conch
-** is held by another process (with a shared lock), the exclusive lock
-** will fail and SQLITE_BUSY is returned.
-**
-** The proxy file - a single-byte file used for all advisory file locks
-** normally taken on the database file. This allows for safe sharing
-** of the database file for multiple readers and writers on the same
-** host (the conch ensures that they all use the same local lock file).
-**
-** Requesting the lock proxy does not immediately take the conch, it is
-** only taken when the first request to lock database file is made.
-** This matches the semantics of the traditional locking behavior, where
-** opening a connection to a database file does not take a lock on it.
-** The shared lock and an open file descriptor are maintained until
-** the connection to the database is closed.
-**
-** The proxy file and the lock file are never deleted so they only need
-** to be created the first time they are used.
-**
-** Configuration options
-** ---------------------
-**
-** SQLITE_PREFER_PROXY_LOCKING
-**
-** Database files accessed on non-local file systems are
-** automatically configured for proxy locking, lock files are
-** named automatically using the same logic as
-** PRAGMA lock_proxy_file=":auto:"
-**
-** SQLITE_PROXY_DEBUG
-**
-** Enables the logging of error messages during host id file
-** retrieval and creation
-**
-** LOCKPROXYDIR
-**
-** Overrides the default directory used for lock proxy files that
-** are named automatically via the ":auto:" setting
-**
-** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
-**
-** Permissions to use when creating a directory for storing the
-** lock proxy files, only used when LOCKPROXYDIR is not set.
-**
-**
-** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
-** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
-** force proxy locking to be used for every database file opened, and 0
-** will force automatic proxy locking to be disabled for all database
-** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
-** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
-*/
-
-/*
-** Proxy locking is only available on MacOSX
-*/
-#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-
-/*
-** The proxyLockingContext has the path and file structures for the remote
-** and local proxy files in it
-*/
-typedef struct proxyLockingContext proxyLockingContext;
-struct proxyLockingContext {
- unixFile *conchFile; /* Open conch file */
- char *conchFilePath; /* Name of the conch file */
- unixFile *lockProxy; /* Open proxy lock file */
- char *lockProxyPath; /* Name of the proxy lock file */
- char *dbPath; /* Name of the open file */
- int conchHeld; /* 1 if the conch is held, -1 if lockless */
- int nFails; /* Number of conch taking failures */
- void *oldLockingContext; /* Original lockingcontext to restore on close */
- sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
-};
-
-/*
-** The proxy lock file path for the database at dbPath is written into lPath,
-** which must point to valid, writable memory large enough for a maxLen length
-** file path.
-*/
-static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
- int len;
- int dbLen;
- int i;
-
-#ifdef LOCKPROXYDIR
- len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
-#else
-# ifdef _CS_DARWIN_USER_TEMP_DIR
- {
- if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
- OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
- lPath, errno, osGetpid(0)));
- return SQLITE_IOERR_LOCK;
- }
- len = strlcat(lPath, "sqliteplocks", maxLen);
- }
-# else
- len = strlcpy(lPath, "/tmp/", maxLen);
-# endif
-#endif
-
- if( lPath[len-1]!='/' ){
- len = strlcat(lPath, "/", maxLen);
- }
-
- /* transform the db path to a unique cache name */
- dbLen = (int)strlen(dbPath);
- for( i=0; i 0) ){
- /* only mkdir if leaf dir != "." or "/" or ".." */
- if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
- || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
- buf[i]='\0';
- if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
- int err=errno;
- if( err!=EEXIST ) {
- OSTRACE(("CREATELOCKPATH FAILED creating %s, "
- "'%s' proxy lock path=%s pid=%d\n",
- buf, strerror(err), lockPath, osGetpid(0)));
- return err;
- }
- }
- }
- start=i+1;
- }
- buf[i] = lockPath[i];
- }
- OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
- return 0;
-}
-
-/*
-** Create a new VFS file descriptor (stored in memory obtained from
-** sqlite3_malloc) and open the file named "path" in the file descriptor.
-**
-** The caller is responsible not only for closing the file descriptor
-** but also for freeing the memory associated with the file descriptor.
-*/
-static int proxyCreateUnixFile(
- const char *path, /* path for the new unixFile */
- unixFile **ppFile, /* unixFile created and returned by ref */
- int islockfile /* if non zero missing dirs will be created */
-) {
- int fd = -1;
- unixFile *pNew;
- int rc = SQLITE_OK;
- int openFlags = O_RDWR | O_CREAT;
- sqlite3_vfs dummyVfs;
- int terrno = 0;
- UnixUnusedFd *pUnused = NULL;
-
- /* 1. first try to open/create the file
- ** 2. if that fails, and this is a lock file (not-conch), try creating
- ** the parent directories and then try again.
- ** 3. if that fails, try to open the file read-only
- ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
- */
- pUnused = findReusableFd(path, openFlags);
- if( pUnused ){
- fd = pUnused->fd;
- }else{
- pUnused = sqlite3_malloc64(sizeof(*pUnused));
- if( !pUnused ){
- return SQLITE_NOMEM_BKPT;
- }
- }
- if( fd<0 ){
- fd = robust_open(path, openFlags, 0);
- terrno = errno;
- if( fd<0 && errno==ENOENT && islockfile ){
- if( proxyCreateLockPath(path) == SQLITE_OK ){
- fd = robust_open(path, openFlags, 0);
- }
- }
- }
- if( fd<0 ){
- openFlags = O_RDONLY;
- fd = robust_open(path, openFlags, 0);
- terrno = errno;
- }
- if( fd<0 ){
- if( islockfile ){
- return SQLITE_BUSY;
- }
- switch (terrno) {
- case EACCES:
- return SQLITE_PERM;
- case EIO:
- return SQLITE_IOERR_LOCK; /* even though it is the conch */
- default:
- return SQLITE_CANTOPEN_BKPT;
- }
- }
-
- pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
- if( pNew==NULL ){
- rc = SQLITE_NOMEM_BKPT;
- goto end_create_proxy;
- }
- memset(pNew, 0, sizeof(unixFile));
- pNew->openFlags = openFlags;
- memset(&dummyVfs, 0, sizeof(dummyVfs));
- dummyVfs.pAppData = (void*)&autolockIoFinder;
- dummyVfs.zName = "dummy";
- pUnused->fd = fd;
- pUnused->flags = openFlags;
- pNew->pPreallocatedUnused = pUnused;
-
- rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
- if( rc==SQLITE_OK ){
- *ppFile = pNew;
- return SQLITE_OK;
- }
-end_create_proxy:
- robust_close(pNew, fd, __LINE__);
- sqlite3_free(pNew);
- sqlite3_free(pUnused);
- return rc;
-}
-
-#ifdef SQLITE_TEST
-/* simulate multiple hosts by creating unique hostid file paths */
-SQLITE_API int sqlite3_hostid_num = 0;
-#endif
-
-#define PROXY_HOSTIDLEN 16 /* conch file host id length */
-
-#ifdef HAVE_GETHOSTUUID
-/* Not always defined in the headers as it ought to be */
-extern int gethostuuid(uuid_t id, const struct timespec *wait);
-#endif
-
-/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
-** bytes of writable memory.
-*/
-static int proxyGetHostID(unsigned char *pHostID, int *pError){
- assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
- memset(pHostID, 0, PROXY_HOSTIDLEN);
-#ifdef HAVE_GETHOSTUUID
- {
- struct timespec timeout = {1, 0}; /* 1 sec timeout */
- if( gethostuuid(pHostID, &timeout) ){
- int err = errno;
- if( pError ){
- *pError = err;
- }
- return SQLITE_IOERR;
- }
- }
-#else
- UNUSED_PARAMETER(pError);
-#endif
-#ifdef SQLITE_TEST
- /* simulate multiple hosts by creating unique hostid file paths */
- if( sqlite3_hostid_num != 0){
- pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
- }
-#endif
-
- return SQLITE_OK;
-}
-
-/* The conch file contains the header, host id and lock file path
- */
-#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
-#define PROXY_HEADERLEN 1 /* conch file header length */
-#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
-#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
-
-/*
-** Takes an open conch file, copies the contents to a new path and then moves
-** it back. The newly created file's file descriptor is assigned to the
-** conch file structure and finally the original conch file descriptor is
-** closed. Returns zero if successful.
-*/
-static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- unixFile *conchFile = pCtx->conchFile;
- char tPath[MAXPATHLEN];
- char buf[PROXY_MAXCONCHLEN];
- char *cPath = pCtx->conchFilePath;
- size_t readLen = 0;
- size_t pathLen = 0;
- char errmsg[64] = "";
- int fd = -1;
- int rc = -1;
- UNUSED_PARAMETER(myHostID);
-
- /* create a new path by replace the trailing '-conch' with '-break' */
- pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
- if( pathLen>MAXPATHLEN || pathLen<6 ||
- (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
- sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
- goto end_breaklock;
- }
- /* read the conch content */
- readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
- if( readLenh, __LINE__);
- conchFile->h = fd;
- conchFile->openFlags = O_RDWR | O_CREAT;
-
-end_breaklock:
- if( rc ){
- if( fd>=0 ){
- osUnlink(tPath);
- robust_close(pFile, fd, __LINE__);
- }
- fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
- }
- return rc;
-}
-
-/* Take the requested lock on the conch file and break a stale lock if the
-** host id matches.
-*/
-static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- unixFile *conchFile = pCtx->conchFile;
- int rc = SQLITE_OK;
- int nTries = 0;
- struct timespec conchModTime;
-
- memset(&conchModTime, 0, sizeof(conchModTime));
- do {
- rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
- nTries ++;
- if( rc==SQLITE_BUSY ){
- /* If the lock failed (busy):
- * 1st try: get the mod time of the conch, wait 0.5s and try again.
- * 2nd try: fail if the mod time changed or host id is different, wait
- * 10 sec and try again
- * 3rd try: break the lock unless the mod time has changed.
- */
- struct stat buf;
- if( osFstat(conchFile->h, &buf) ){
- storeLastErrno(pFile, errno);
- return SQLITE_IOERR_LOCK;
- }
-
- if( nTries==1 ){
- conchModTime = buf.st_mtimespec;
- usleep(500000); /* wait 0.5 sec and try the lock again*/
- continue;
- }
-
- assert( nTries>1 );
- if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
- conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
- return SQLITE_BUSY;
- }
-
- if( nTries==2 ){
- char tBuf[PROXY_MAXCONCHLEN];
- int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
- if( len<0 ){
- storeLastErrno(pFile, errno);
- return SQLITE_IOERR_LOCK;
- }
- if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
- /* don't break the lock if the host id doesn't match */
- if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
- return SQLITE_BUSY;
- }
- }else{
- /* don't break the lock on short read or a version mismatch */
- return SQLITE_BUSY;
- }
- usleep(10000000); /* wait 10 sec and try the lock again */
- continue;
- }
-
- assert( nTries==3 );
- if( 0==proxyBreakConchLock(pFile, myHostID) ){
- rc = SQLITE_OK;
- if( lockType==EXCLUSIVE_LOCK ){
- rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
- }
- if( !rc ){
- rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
- }
- }
- }
- } while( rc==SQLITE_BUSY && nTries<3 );
-
- return rc;
-}
-
-/* Takes the conch by taking a shared lock and read the contents conch, if
-** lockPath is non-NULL, the host ID and lock file path must match. A NULL
-** lockPath means that the lockPath in the conch file will be used if the
-** host IDs match, or a new lock path will be generated automatically
-** and written to the conch file.
-*/
-static int proxyTakeConch(unixFile *pFile){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
-
- if( pCtx->conchHeld!=0 ){
- return SQLITE_OK;
- }else{
- unixFile *conchFile = pCtx->conchFile;
- uuid_t myHostID;
- int pError = 0;
- char readBuf[PROXY_MAXCONCHLEN];
- char lockPath[MAXPATHLEN];
- char *tempLockPath = NULL;
- int rc = SQLITE_OK;
- int createConch = 0;
- int hostIdMatch = 0;
- int readLen = 0;
- int tryOldLockPath = 0;
- int forceNewLockPath = 0;
-
- OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
- (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
- osGetpid(0)));
-
- rc = proxyGetHostID(myHostID, &pError);
- if( (rc&0xff)==SQLITE_IOERR ){
- storeLastErrno(pFile, pError);
- goto end_takeconch;
- }
- rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
- if( rc!=SQLITE_OK ){
- goto end_takeconch;
- }
- /* read the existing conch file */
- readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
- if( readLen<0 ){
- /* I/O error: lastErrno set by seekAndRead */
- storeLastErrno(pFile, conchFile->lastErrno);
- rc = SQLITE_IOERR_READ;
- goto end_takeconch;
- }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
- readBuf[0]!=(char)PROXY_CONCHVERSION ){
- /* a short read or version format mismatch means we need to create a new
- ** conch file.
- */
- createConch = 1;
- }
- /* if the host id matches and the lock path already exists in the conch
- ** we'll try to use the path there, if we can't open that path, we'll
- ** retry with a new auto-generated path
- */
- do { /* in case we need to try again for an :auto: named lock file */
-
- if( !createConch && !forceNewLockPath ){
- hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
- PROXY_HOSTIDLEN);
- /* if the conch has data compare the contents */
- if( !pCtx->lockProxyPath ){
- /* for auto-named local lock file, just check the host ID and we'll
- ** use the local lock file path that's already in there
- */
- if( hostIdMatch ){
- size_t pathLen = (readLen - PROXY_PATHINDEX);
-
- if( pathLen>=MAXPATHLEN ){
- pathLen=MAXPATHLEN-1;
- }
- memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
- lockPath[pathLen] = 0;
- tempLockPath = lockPath;
- tryOldLockPath = 1;
- /* create a copy of the lock path if the conch is taken */
- goto end_takeconch;
- }
- }else if( hostIdMatch
- && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
- readLen-PROXY_PATHINDEX)
- ){
- /* conch host and lock path match */
- goto end_takeconch;
- }
- }
-
- /* if the conch isn't writable and doesn't match, we can't take it */
- if( (conchFile->openFlags&O_RDWR) == 0 ){
- rc = SQLITE_BUSY;
- goto end_takeconch;
- }
-
- /* either the conch didn't match or we need to create a new one */
- if( !pCtx->lockProxyPath ){
- proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
- tempLockPath = lockPath;
- /* create a copy of the lock path _only_ if the conch is taken */
- }
-
- /* update conch with host and path (this will fail if other process
- ** has a shared lock already), if the host id matches, use the big
- ** stick.
- */
- futimes(conchFile->h, NULL);
- if( hostIdMatch && !createConch ){
- if( conchFile->pInode && conchFile->pInode->nShared>1 ){
- /* We are trying for an exclusive lock but another thread in this
- ** same process is still holding a shared lock. */
- rc = SQLITE_BUSY;
- } else {
- rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
- }
- }else{
- rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
- }
- if( rc==SQLITE_OK ){
- char writeBuffer[PROXY_MAXCONCHLEN];
- int writeSize = 0;
-
- writeBuffer[0] = (char)PROXY_CONCHVERSION;
- memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
- if( pCtx->lockProxyPath!=NULL ){
- strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
- MAXPATHLEN);
- }else{
- strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
- }
- writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
- robust_ftruncate(conchFile->h, writeSize);
- rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
- full_fsync(conchFile->h,0,0);
- /* If we created a new conch file (not just updated the contents of a
- ** valid conch file), try to match the permissions of the database
- */
- if( rc==SQLITE_OK && createConch ){
- struct stat buf;
- int err = osFstat(pFile->h, &buf);
- if( err==0 ){
- mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
- S_IROTH|S_IWOTH);
- /* try to match the database file R/W permissions, ignore failure */
-#ifndef SQLITE_PROXY_DEBUG
- osFchmod(conchFile->h, cmode);
-#else
- do{
- rc = osFchmod(conchFile->h, cmode);
- }while( rc==(-1) && errno==EINTR );
- if( rc!=0 ){
- int code = errno;
- fprintf(stderr, "fchmod %o FAILED with %d %s\n",
- cmode, code, strerror(code));
- } else {
- fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
- }
- }else{
- int code = errno;
- fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
- err, code, strerror(code));
-#endif
- }
- }
- }
- conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
-
- end_takeconch:
- OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
- if( rc==SQLITE_OK && pFile->openFlags ){
- int fd;
- if( pFile->h>=0 ){
- robust_close(pFile, pFile->h, __LINE__);
- }
- pFile->h = -1;
- fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
- OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
- if( fd>=0 ){
- pFile->h = fd;
- }else{
- rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
- during locking */
- }
- }
- if( rc==SQLITE_OK && !pCtx->lockProxy ){
- char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
- rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
- if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
- /* we couldn't create the proxy lock file with the old lock file path
- ** so try again via auto-naming
- */
- forceNewLockPath = 1;
- tryOldLockPath = 0;
- continue; /* go back to the do {} while start point, try again */
- }
- }
- if( rc==SQLITE_OK ){
- /* Need to make a copy of path if we extracted the value
- ** from the conch file or the path was allocated on the stack
- */
- if( tempLockPath ){
- pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
- if( !pCtx->lockProxyPath ){
- rc = SQLITE_NOMEM_BKPT;
- }
- }
- }
- if( rc==SQLITE_OK ){
- pCtx->conchHeld = 1;
-
- if( pCtx->lockProxy->pMethod == &afpIoMethods ){
- afpLockingContext *afpCtx;
- afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
- afpCtx->dbPath = pCtx->lockProxyPath;
- }
- } else {
- conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
- }
- OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
- rc==SQLITE_OK?"ok":"failed"));
- return rc;
- } while (1); /* in case we need to retry the :auto: lock file -
- ** we should never get here except via the 'continue' call. */
- }
-}
-
-/*
-** If pFile holds a lock on a conch file, then release that lock.
-*/
-static int proxyReleaseConch(unixFile *pFile){
- int rc = SQLITE_OK; /* Subroutine return code */
- proxyLockingContext *pCtx; /* The locking context for the proxy lock */
- unixFile *conchFile; /* Name of the conch file */
-
- pCtx = (proxyLockingContext *)pFile->lockingContext;
- conchFile = pCtx->conchFile;
- OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
- (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
- osGetpid(0)));
- if( pCtx->conchHeld>0 ){
- rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
- }
- pCtx->conchHeld = 0;
- OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
- (rc==SQLITE_OK ? "ok" : "failed")));
- return rc;
-}
-
-/*
-** Given the name of a database file, compute the name of its conch file.
-** Store the conch filename in memory obtained from sqlite3_malloc64().
-** Make *pConchPath point to the new name. Return SQLITE_OK on success
-** or SQLITE_NOMEM if unable to obtain memory.
-**
-** The caller is responsible for ensuring that the allocated memory
-** space is eventually freed.
-**
-** *pConchPath is set to NULL if a memory allocation error occurs.
-*/
-static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
- int i; /* Loop counter */
- int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
- char *conchPath; /* buffer in which to construct conch name */
-
- /* Allocate space for the conch filename and initialize the name to
- ** the name of the original database file. */
- *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
- if( conchPath==0 ){
- return SQLITE_NOMEM_BKPT;
- }
- memcpy(conchPath, dbPath, len+1);
-
- /* now insert a "." before the last / character */
- for( i=(len-1); i>=0; i-- ){
- if( conchPath[i]=='/' ){
- i++;
- break;
- }
- }
- conchPath[i]='.';
- while ( ilockingContext;
- char *oldPath = pCtx->lockProxyPath;
- int rc = SQLITE_OK;
-
- if( pFile->eFileLock!=NO_LOCK ){
- return SQLITE_BUSY;
- }
-
- /* nothing to do if the path is NULL, :auto: or matches the existing path */
- if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
- (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
- return SQLITE_OK;
- }else{
- unixFile *lockProxy = pCtx->lockProxy;
- pCtx->lockProxy=NULL;
- pCtx->conchHeld = 0;
- if( lockProxy!=NULL ){
- rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
- if( rc ) return rc;
- sqlite3_free(lockProxy);
- }
- sqlite3_free(oldPath);
- pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
- }
-
- return rc;
-}
-
-/*
-** pFile is a file that has been opened by a prior xOpen call. dbPath
-** is a string buffer at least MAXPATHLEN+1 characters in size.
-**
-** This routine find the filename associated with pFile and writes it
-** int dbPath.
-*/
-static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
-#if defined(__APPLE__)
- if( pFile->pMethod == &afpIoMethods ){
- /* afp style keeps a reference to the db path in the filePath field
- ** of the struct */
- assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
- strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
- MAXPATHLEN);
- } else
-#endif
- if( pFile->pMethod == &dotlockIoMethods ){
- /* dot lock style uses the locking context to store the dot lock
- ** file path */
- int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
- memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
- }else{
- /* all other styles use the locking context to store the db file path */
- assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
- strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
- }
- return SQLITE_OK;
-}
-
-/*
-** Takes an already filled in unix file and alters it so all file locking
-** will be performed on the local proxy lock file. The following fields
-** are preserved in the locking context so that they can be restored and
-** the unix structure properly cleaned up at close time:
-** ->lockingContext
-** ->pMethod
-*/
-static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
- proxyLockingContext *pCtx;
- char dbPath[MAXPATHLEN+1]; /* Name of the database file */
- char *lockPath=NULL;
- int rc = SQLITE_OK;
-
- if( pFile->eFileLock!=NO_LOCK ){
- return SQLITE_BUSY;
- }
- proxyGetDbPathForUnixFile(pFile, dbPath);
- if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
- lockPath=NULL;
- }else{
- lockPath=(char *)path;
- }
-
- OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
- (lockPath ? lockPath : ":auto:"), osGetpid(0)));
-
- pCtx = sqlite3_malloc64( sizeof(*pCtx) );
- if( pCtx==0 ){
- return SQLITE_NOMEM_BKPT;
- }
- memset(pCtx, 0, sizeof(*pCtx));
-
- rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
- if( rc==SQLITE_OK ){
- rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
- if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
- /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
- ** (c) the file system is read-only, then enable no-locking access.
- ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
- ** that openFlags will have only one of O_RDONLY or O_RDWR.
- */
- struct statfs fsInfo;
- struct stat conchInfo;
- int goLockless = 0;
-
- if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
- int err = errno;
- if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
- goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
- }
- }
- if( goLockless ){
- pCtx->conchHeld = -1; /* read only FS/ lockless */
- rc = SQLITE_OK;
- }
- }
- }
- if( rc==SQLITE_OK && lockPath ){
- pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
- }
-
- if( rc==SQLITE_OK ){
- pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
- if( pCtx->dbPath==NULL ){
- rc = SQLITE_NOMEM_BKPT;
- }
- }
- if( rc==SQLITE_OK ){
- /* all memory is allocated, proxys are created and assigned,
- ** switch the locking context and pMethod then return.
- */
- pCtx->oldLockingContext = pFile->lockingContext;
- pFile->lockingContext = pCtx;
- pCtx->pOldMethod = pFile->pMethod;
- pFile->pMethod = &proxyIoMethods;
- }else{
- if( pCtx->conchFile ){
- pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
- sqlite3_free(pCtx->conchFile);
- }
- sqlite3DbFree(0, pCtx->lockProxyPath);
- sqlite3_free(pCtx->conchFilePath);
- sqlite3_free(pCtx);
- }
- OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
- (rc==SQLITE_OK ? "ok" : "failed")));
- return rc;
-}
-
-
-/*
-** This routine handles sqlite3_file_control() calls that are specific
-** to proxy locking.
-*/
-static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
- switch( op ){
- case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
- unixFile *pFile = (unixFile*)id;
- if( pFile->pMethod == &proxyIoMethods ){
- proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
- proxyTakeConch(pFile);
- if( pCtx->lockProxyPath ){
- *(const char **)pArg = pCtx->lockProxyPath;
- }else{
- *(const char **)pArg = ":auto: (not held)";
- }
- } else {
- *(const char **)pArg = NULL;
- }
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
- unixFile *pFile = (unixFile*)id;
- int rc = SQLITE_OK;
- int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
- if( pArg==NULL || (const char *)pArg==0 ){
- if( isProxyStyle ){
- /* turn off proxy locking - not supported. If support is added for
- ** switching proxy locking mode off then it will need to fail if
- ** the journal mode is WAL mode.
- */
- rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
- }else{
- /* turn off proxy locking - already off - NOOP */
- rc = SQLITE_OK;
- }
- }else{
- const char *proxyPath = (const char *)pArg;
- if( isProxyStyle ){
- proxyLockingContext *pCtx =
- (proxyLockingContext*)pFile->lockingContext;
- if( !strcmp(pArg, ":auto:")
- || (pCtx->lockProxyPath &&
- !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
- ){
- rc = SQLITE_OK;
- }else{
- rc = switchLockProxyPath(pFile, proxyPath);
- }
- }else{
- /* turn on proxy file locking */
- rc = proxyTransformUnixFile(pFile, proxyPath);
- }
- }
- return rc;
- }
- default: {
- assert( 0 ); /* The call assures that only valid opcodes are sent */
- }
- }
- /*NOTREACHED*/
- return SQLITE_ERROR;
-}
-
-/*
-** Within this division (the proxying locking implementation) the procedures
-** above this point are all utilities. The lock-related methods of the
-** proxy-locking sqlite3_io_method object follow.
-*/
-
-
-/*
-** 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, set *pResOut
-** to a non-zero value otherwise *pResOut is set to zero. The return value
-** is set to SQLITE_OK unless an I/O error occurs during lock checking.
-*/
-static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
- unixFile *pFile = (unixFile*)id;
- int rc = proxyTakeConch(pFile);
- if( rc==SQLITE_OK ){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- if( pCtx->conchHeld>0 ){
- unixFile *proxy = pCtx->lockProxy;
- return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
- }else{ /* conchHeld < 0 is lockless */
- pResOut=0;
- }
- }
- return rc;
-}
-
-/*
-** Lock the file with the lock specified by parameter eFileLock - 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. Use the sqlite3OsUnlock()
-** routine to lower a locking level.
-*/
-static int proxyLock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- int rc = proxyTakeConch(pFile);
- if( rc==SQLITE_OK ){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- if( pCtx->conchHeld>0 ){
- unixFile *proxy = pCtx->lockProxy;
- rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
- pFile->eFileLock = proxy->eFileLock;
- }else{
- /* conchHeld < 0 is lockless */
- }
- }
- return rc;
-}
-
-
-/*
-** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
-** 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.
-*/
-static int proxyUnlock(sqlite3_file *id, int eFileLock) {
- unixFile *pFile = (unixFile*)id;
- int rc = proxyTakeConch(pFile);
- if( rc==SQLITE_OK ){
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- if( pCtx->conchHeld>0 ){
- unixFile *proxy = pCtx->lockProxy;
- rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
- pFile->eFileLock = proxy->eFileLock;
- }else{
- /* conchHeld < 0 is lockless */
- }
- }
- return rc;
-}
-
-/*
-** Close a file that uses proxy locks.
-*/
-static int proxyClose(sqlite3_file *id) {
- if( ALWAYS(id) ){
- unixFile *pFile = (unixFile*)id;
- proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
- unixFile *lockProxy = pCtx->lockProxy;
- unixFile *conchFile = pCtx->conchFile;
- int rc = SQLITE_OK;
-
- if( lockProxy ){
- rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
- if( rc ) return rc;
- rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
- if( rc ) return rc;
- sqlite3_free(lockProxy);
- pCtx->lockProxy = 0;
- }
- if( conchFile ){
- if( pCtx->conchHeld ){
- rc = proxyReleaseConch(pFile);
- if( rc ) return rc;
- }
- rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
- if( rc ) return rc;
- sqlite3_free(conchFile);
- }
- sqlite3DbFree(0, pCtx->lockProxyPath);
- sqlite3_free(pCtx->conchFilePath);
- sqlite3DbFree(0, pCtx->dbPath);
- /* restore the original locking context and pMethod then close it */
- pFile->lockingContext = pCtx->oldLockingContext;
- pFile->pMethod = pCtx->pOldMethod;
- sqlite3_free(pCtx);
- return pFile->pMethod->xClose(id);
- }
- return SQLITE_OK;
-}
-
-
-
-#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
-/*
-** The proxy locking style is intended for use with AFP filesystems.
-** And since AFP is only supported on MacOSX, the proxy locking is also
-** restricted to MacOSX.
-**
-**
-******************* End of the proxy lock implementation **********************
-******************************************************************************/
-
-/*
-** Initialize the operating system interface.
-**
-** This routine registers all VFS implementations for unix-like operating
-** systems. This routine, and the sqlite3_os_end() routine that follows,
-** should be the only routines in this file that are visible from other
-** files.
-**
-** This routine is called once during SQLite initialization and by a
-** single thread. The memory allocation and mutex subsystems have not
-** necessarily been initialized when this routine is called, and so they
-** should not be used.
-*/
-SQLITE_API int sqlite3_os_init(void){
- /*
- ** The following macro defines an initializer for an sqlite3_vfs object.
- ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
- ** to the "finder" function. (pAppData is a pointer to a pointer because
- ** silly C90 rules prohibit a void* from being cast to a function pointer
- ** and so we have to go through the intermediate pointer to avoid problems
- ** when compiling with -pedantic-errors on GCC.)
- **
- ** The FINDER parameter to this macro is the name of the pointer to the
- ** finder-function. The finder-function returns a pointer to the
- ** sqlite_io_methods object that implements the desired locking
- ** behaviors. See the division above that contains the IOMETHODS
- ** macro for addition information on finder-functions.
- **
- ** Most finders simply return a pointer to a fixed sqlite3_io_methods
- ** object. But the "autolockIoFinder" available on MacOSX does a little
- ** more than that; it looks at the filesystem type that hosts the
- ** database file and tries to choose an locking method appropriate for
- ** that filesystem time.
- */
- #define UNIXVFS(VFSNAME, FINDER) { \
- 3, /* iVersion */ \
- sizeof(unixFile), /* szOsFile */ \
- MAX_PATHNAME, /* mxPathname */ \
- 0, /* pNext */ \
- VFSNAME, /* zName */ \
- (void*)&FINDER, /* pAppData */ \
- unixOpen, /* xOpen */ \
- unixDelete, /* xDelete */ \
- unixAccess, /* xAccess */ \
- unixFullPathname, /* xFullPathname */ \
- unixDlOpen, /* xDlOpen */ \
- unixDlError, /* xDlError */ \
- unixDlSym, /* xDlSym */ \
- unixDlClose, /* xDlClose */ \
- unixRandomness, /* xRandomness */ \
- unixSleep, /* xSleep */ \
- unixCurrentTime, /* xCurrentTime */ \
- unixGetLastError, /* xGetLastError */ \
- unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
- unixSetSystemCall, /* xSetSystemCall */ \
- unixGetSystemCall, /* xGetSystemCall */ \
- unixNextSystemCall, /* xNextSystemCall */ \
- }
-
- /*
- ** All default VFSes for unix are contained in the following array.
- **
- ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
- ** by the SQLite core when the VFS is registered. So the following
- ** array cannot be const.
- */
- static sqlite3_vfs aVfs[] = {
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
- UNIXVFS("unix", autolockIoFinder ),
-#elif OS_VXWORKS
- UNIXVFS("unix", vxworksIoFinder ),
-#else
- UNIXVFS("unix", posixIoFinder ),
-#endif
- UNIXVFS("unix-none", nolockIoFinder ),
- UNIXVFS("unix-dotfile", dotlockIoFinder ),
- UNIXVFS("unix-excl", posixIoFinder ),
-#if OS_VXWORKS
- UNIXVFS("unix-namedsem", semIoFinder ),
-#endif
-#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
- UNIXVFS("unix-posix", posixIoFinder ),
-#endif
-#if SQLITE_ENABLE_LOCKING_STYLE
- UNIXVFS("unix-flock", flockIoFinder ),
-#endif
-#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
- UNIXVFS("unix-afp", afpIoFinder ),
- UNIXVFS("unix-nfs", nfsIoFinder ),
- UNIXVFS("unix-proxy", proxyIoFinder ),
-#endif
- };
- unsigned int i; /* Loop counter */
-
- /* Double-check that the aSyscall[] array has been constructed
- ** correctly. See ticket [bb3a86e890c8e96ab] */
- assert( ArraySize(aSyscall)==29 );
-
- /* Register all VFSes defined in the aVfs[] array */
- for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
- sqlite3_vfs_register(&aVfs[i], i==0);
- }
- unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
- return SQLITE_OK;
-}
-
-/*
-** Shutdown the operating system interface.
-**
-** Some operating systems might need to do some cleanup in this routine,
-** to release dynamically allocated objects. But not on unix.
-** This routine is a no-op for unix.
-*/
-SQLITE_API int sqlite3_os_end(void){
- unixBigLock = 0;
- return SQLITE_OK;
-}
-
-#endif /* SQLITE_OS_UNIX */
-
-/************** End of os_unix.c *********************************************/
-/************** Begin file os_win.c ******************************************/
-/*
-** 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.
-*/
-/* #include "sqliteInt.h" */
-#if SQLITE_OS_WIN /* This file is used for Windows only */
-
-/*
-** Include code that is common to all os_*.c files
-*/
-/************** Include os_common.h in the middle of os_win.c ****************/
-/************** Begin file os_common.h ***************************************/
-/*
-** 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.
-*/
-#ifndef _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.
-*/
-#ifdef MEMORY_DEBUG
-# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
-#endif
-
-/*
-** Macros for performance tracing. Normally turned off. Only works
-** on i486 hardware.
-*/
-#ifdef SQLITE_PERFORMANCE_TRACE
-
-/*
-** hwtime.h contains inline assembler code for implementing
-** high-performance timing routines.
-*/
-/************** Include hwtime.h in the middle of os_common.h ****************/
-/************** Begin file hwtime.h ******************************************/
-/*
-** 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.
-*/
-#ifndef SQLITE_HWTIME_H
-#define SQLITE_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 (defined(__GNUC__) || defined(_MSC_VER)) && \
- (defined(i386) || defined(__i386__) || defined(_M_IX86))
-
- #if defined(__GNUC__)
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned int lo, hi;
- __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
- return (sqlite_uint64)hi << 32 | lo;
- }
-
- #elif defined(_MSC_VER)
-
- __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
- __asm {
- rdtsc
- ret ; return value at EDX:EAX
- }
- }
-
- #endif
-
-#elif (defined(__GNUC__) && defined(__x86_64__))
-
- __inline__ sqlite_uint64 sqlite3Hwtime(void){
- unsigned long val;
- __asm__ __volatile__ ("rdtsc" : "=A" (val));
- return val;
- }
-
-#elif (defined(__GNUC__) && defined(__ppc__))
-
- __inline__ sqlite_uint64 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.
- */
-SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
-
-#endif
-
-#endif /* !defined(SQLITE_HWTIME_H) */
-
-/************** End of hwtime.h **********************************************/
-/************** Continuing where we left off in os_common.h ******************/
-
-static sqlite_uint64 g_start;
-static sqlite_uint64 g_elapsed;
-#define TIMER_START g_start=sqlite3Hwtime()
-#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
-#define TIMER_ELAPSED g_elapsed
-#else
-#define TIMER_START
-#define TIMER_END
-#define TIMER_ELAPSED ((sqlite_uint64)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 defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_io_error_hit;
-SQLITE_API extern int sqlite3_io_error_hardhit;
-SQLITE_API extern int sqlite3_io_error_pending;
-SQLITE_API extern int sqlite3_io_error_persist;
-SQLITE_API extern int sqlite3_io_error_benign;
-SQLITE_API extern int sqlite3_diskfull_pending;
-SQLITE_API extern int sqlite3_diskfull;
-#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
-#define SimulateIOError(CODE) \
- if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
- || sqlite3_io_error_pending-- == 1 ) \
- { local_ioerr(); CODE; }
-static void local_ioerr(){
- IOTRACE(("IOERR\n"));
- sqlite3_io_error_hit++;
- if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
-}
-#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--; \
- } \
- }
-#else
-#define SimulateIOErrorBenign(X)
-#define SimulateIOError(A)
-#define SimulateDiskfullError(A)
-#endif /* defined(SQLITE_TEST) */
-
-/*
-** When testing, keep a count of the number of open files.
-*/
-#if defined(SQLITE_TEST)
-SQLITE_API extern int sqlite3_open_file_count;
-#define OpenCounter(X) sqlite3_open_file_count+=(X)
-#else
-#define OpenCounter(X)
-#endif /* defined(SQLITE_TEST) */
-
-#endif /* !defined(_OS_COMMON_H_) */
-
-/************** End of os_common.h *******************************************/
-/************** Continuing where we left off in os_win.c *********************/
-
-/*
-** Include the header file for the Windows VFS.
-*/
-/* #include "os_win.h" */
-
-/*
-** Compiling and using WAL mode requires several APIs that are only
-** available in Windows platforms based on the NT kernel.
-*/
-#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
-# error "WAL mode requires support from the Windows NT kernel, compile\
- with SQLITE_OMIT_WAL."
-#endif
-
-#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
-# error "Memory mapped files require support from the Windows NT kernel,\
- compile with SQLITE_MAX_MMAP_SIZE=0."
-#endif
-
-/*
-** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
-** based on the sub-platform)?
-*/
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
-# define SQLITE_WIN32_HAS_ANSI
-#endif
-
-/*
-** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
-** based on the sub-platform)?
-*/
-#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
- !defined(SQLITE_WIN32_NO_WIDE)
-# define SQLITE_WIN32_HAS_WIDE
-#endif
-
-/*
-** Make sure at least one set of Win32 APIs is available.
-*/
-#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
-# error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
- must be defined."
-#endif
-
-/*
-** Define the required Windows SDK version constants if they are not
-** already available.
-*/
-#ifndef NTDDI_WIN8
-# define NTDDI_WIN8 0x06020000
-#endif
-
-#ifndef NTDDI_WINBLUE
-# define NTDDI_WINBLUE 0x06030000
-#endif
-
-#ifndef NTDDI_WINTHRESHOLD
-# define NTDDI_WINTHRESHOLD 0x06040000
-#endif
-
-/*
-** Check to see if the GetVersionEx[AW] functions are deprecated on the
-** target system. GetVersionEx was first deprecated in Win8.1.
-*/
-#ifndef SQLITE_WIN32_GETVERSIONEX
-# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
-# define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
-# else
-# define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
-# endif
-#endif
-
-/*
-** Check to see if the CreateFileMappingA function is supported on the
-** target system. It is unavailable when using "mincore.lib" on Win10.
-** When compiling for Windows 10, always assume "mincore.lib" is in use.
-*/
-#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
-# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
-# define SQLITE_WIN32_CREATEFILEMAPPINGA 0
-# else
-# define SQLITE_WIN32_CREATEFILEMAPPINGA 1
-# endif
-#endif
-
-/*
-** This constant should already be defined (in the "WinDef.h" SDK file).
-*/
-#ifndef MAX_PATH
-# define MAX_PATH (260)
-#endif
-
-/*
-** Maximum pathname length (in chars) for Win32. This should normally be
-** MAX_PATH.
-*/
-#ifndef SQLITE_WIN32_MAX_PATH_CHARS
-# define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
-#endif
-
-/*
-** This constant should already be defined (in the "WinNT.h" SDK file).
-*/
-#ifndef UNICODE_STRING_MAX_CHARS
-# define UNICODE_STRING_MAX_CHARS (32767)
-#endif
-
-/*
-** Maximum pathname length (in chars) for WinNT. This should normally be
-** UNICODE_STRING_MAX_CHARS.
-*/
-#ifndef SQLITE_WINNT_MAX_PATH_CHARS
-# define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
-#endif
-
-/*
-** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
-** characters, so we allocate 4 bytes per character assuming worst-case of
-** 4-bytes-per-character for UTF8.
-*/
-#ifndef SQLITE_WIN32_MAX_PATH_BYTES
-# define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
-#endif
-
-/*
-** Maximum pathname length (in bytes) for WinNT. This should normally be
-** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
-*/
-#ifndef SQLITE_WINNT_MAX_PATH_BYTES
-# define SQLITE_WINNT_MAX_PATH_BYTES \
- (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
-#endif
-
-/*
-** Maximum error message length (in chars) for WinRT.
-*/
-#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
-# define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
-#endif
-
-/*
-** Returns non-zero if the character should be treated as a directory
-** separator.
-*/
-#ifndef winIsDirSep
-# define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
-#endif
-
-/*
-** This macro is used when a local variable is set to a value that is
-** [sometimes] not used by the code (e.g. via conditional compilation).
-*/
-#ifndef UNUSED_VARIABLE_VALUE
-# define UNUSED_VARIABLE_VALUE(x) (void)(x)
-#endif
-
-/*
-** Returns the character that should be used as the directory separator.
-*/
-#ifndef winGetDirSep
-# define winGetDirSep() '\\'
-#endif
-
-/*
-** Do we need to manually define the Win32 file mapping APIs for use with WAL
-** mode or memory mapped files (e.g. these APIs are available in the Windows
-** CE SDK; however, they are not present in the header file)?
-*/
-#if SQLITE_WIN32_FILEMAPPING_API && \
- (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
-/*
-** Two of the file mapping APIs are different under WinRT. Figure out which
-** set we need.
-*/
-#if SQLITE_OS_WINRT
-WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
- LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
-
-WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
-#else
-#if defined(SQLITE_WIN32_HAS_ANSI)
-WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
- DWORD, DWORD, DWORD, LPCSTR);
-#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
-WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
- DWORD, DWORD, DWORD, LPCWSTR);
-#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
-
-WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
-#endif /* SQLITE_OS_WINRT */
-
-/*
-** These file mapping APIs are common to both Win32 and WinRT.
-*/
-
-WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
-WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
-#endif /* SQLITE_WIN32_FILEMAPPING_API */
-
-/*
-** Some Microsoft compilers lack this definition.
-*/
-#ifndef INVALID_FILE_ATTRIBUTES
-# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
-#endif
-
-#ifndef FILE_FLAG_MASK
-# define FILE_FLAG_MASK (0xFF3C0000)
-#endif
-
-#ifndef FILE_ATTRIBUTE_MASK
-# define FILE_ATTRIBUTE_MASK (0x0003FFF7)
-#endif
-
-#ifndef SQLITE_OMIT_WAL
-/* Forward references to structures used for WAL */
-typedef struct winShm winShm; /* A connection to shared-memory */
-typedef struct winShmNode winShmNode; /* A region of shared-memory */
-#endif
-
-/*
-** WinCE lacks native support for file locking so we have to fake it
-** with some code of our own.
-*/
-#if SQLITE_OS_WINCE
-typedef struct winceLock {
- int nReaders; /* Number of reader locks obtained */
- BOOL bPending; /* Indicates a pending lock has been obtained */
- BOOL bReserved; /* Indicates a reserved lock has been obtained */
- BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
-} winceLock;
-#endif
-
-/*
-** The winFile structure is a subclass of sqlite3_file* specific to the win32
-** portability layer.
-*/
-typedef struct winFile winFile;
-struct winFile {
- const sqlite3_io_methods *pMethod; /*** Must be first ***/
- sqlite3_vfs *pVfs; /* The VFS used to open this file */
- HANDLE h; /* Handle for accessing the file */
- u8 locktype; /* Type of lock currently held on this file */
- short sharedLockByte; /* Randomly chosen byte used as a shared lock */
- u8 ctrlFlags; /* Flags. See WINFILE_* below */
- DWORD lastErrno; /* The Windows errno from the last I/O error */
-#ifndef SQLITE_OMIT_WAL
- winShm *pShm; /* Instance of shared memory on this file */
-#endif
- const char *zPath; /* Full pathname of this file */
- int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
-#if SQLITE_OS_WINCE
- LPWSTR 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 winFile */
- winceLock *shared; /* Global shared lock memory for the file */
-#endif
-#if SQLITE_MAX_MMAP_SIZE>0
- int nFetchOut; /* Number of outstanding xFetch references */
- HANDLE hMap; /* Handle for accessing memory mapping */
- void *pMapRegion; /* Area memory mapped */
- sqlite3_int64 mmapSize; /* Size of mapped region */
- sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
-#endif
-};
-
-/*
-** The winVfsAppData structure is used for the pAppData member for all of the
-** Win32 VFS variants.
-*/
-typedef struct winVfsAppData winVfsAppData;
-struct winVfsAppData {
- const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
- void *pAppData; /* The extra pAppData, if any. */
- BOOL bNoLock; /* Non-zero if locking is disabled. */
-};
-
-/*
-** Allowed values for winFile.ctrlFlags
-*/
-#define WINFILE_RDONLY 0x02 /* Connection is read only */
-#define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
-#define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
-
-/*
- * The size of the buffer used by sqlite3_win32_write_debug().
- */
-#ifndef SQLITE_WIN32_DBG_BUF_SIZE
-# define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
-#endif
-
-/*
- * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
- * various Win32 API heap functions instead of our own.
- */
-#ifdef SQLITE_WIN32_MALLOC
-
-/*
- * If this is non-zero, an isolated heap will be created by the native Win32
- * allocator subsystem; otherwise, the default process heap will be used. This
- * setting has no effect when compiling for WinRT. By default, this is enabled
- * and an isolated heap will be created to store all allocated data.
- *
- ******************************************************************************
- * WARNING: It is important to note that when this setting is non-zero and the
- * winMemShutdown function is called (e.g. by the sqlite3_shutdown
- * function), all data that was allocated using the isolated heap will
- * be freed immediately and any attempt to access any of that freed
- * data will almost certainly result in an immediate access violation.
- ******************************************************************************
- */
-#ifndef SQLITE_WIN32_HEAP_CREATE
-# define SQLITE_WIN32_HEAP_CREATE (TRUE)
-#endif
-
-/*
- * This is the maximum possible initial size of the Win32-specific heap, in
- * bytes.
- */
-#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
-# define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
-#endif
-
-/*
- * This is the extra space for the initial size of the Win32-specific heap,
- * in bytes. This value may be zero.
- */
-#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
-# define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
-#endif
-
-/*
- * Calculate the maximum legal cache size, in pages, based on the maximum
- * possible initial heap size and the default page size, setting aside the
- * needed extra space.
- */
-#ifndef SQLITE_WIN32_MAX_CACHE_SIZE
-# define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
- (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
- (SQLITE_DEFAULT_PAGE_SIZE))
-#endif
-
-/*
- * This is cache size used in the calculation of the initial size of the
- * Win32-specific heap. It cannot be negative.
- */
-#ifndef SQLITE_WIN32_CACHE_SIZE
-# if SQLITE_DEFAULT_CACHE_SIZE>=0
-# define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
-# else
-# define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
-# endif
-#endif
-
-/*
- * Make sure that the calculated cache size, in pages, cannot cause the
- * initial size of the Win32-specific heap to exceed the maximum amount
- * of memory that can be specified in the call to HeapCreate.
- */
-#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
-# undef SQLITE_WIN32_CACHE_SIZE
-# define SQLITE_WIN32_CACHE_SIZE (2000)
-#endif
-
-/*
- * The initial size of the Win32-specific heap. This value may be zero.
- */
-#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
-# define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
- (SQLITE_DEFAULT_PAGE_SIZE) + \
- (SQLITE_WIN32_HEAP_INIT_EXTRA))
-#endif
-
-/*
- * The maximum size of the Win32-specific heap. This value may be zero.
- */
-#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
-# define SQLITE_WIN32_HEAP_MAX_SIZE (0)
-#endif
-
-/*
- * The extra flags to use in calls to the Win32 heap APIs. This value may be
- * zero for the default behavior.
- */
-#ifndef SQLITE_WIN32_HEAP_FLAGS
-# define SQLITE_WIN32_HEAP_FLAGS (0)
-#endif
-
-
-/*
-** The winMemData structure stores information required by the Win32-specific
-** sqlite3_mem_methods implementation.
-*/
-typedef struct winMemData winMemData;
-struct winMemData {
-#ifndef NDEBUG
- u32 magic1; /* Magic number to detect structure corruption. */
-#endif
- HANDLE hHeap; /* The handle to our heap. */
- BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
-#ifndef NDEBUG
- u32 magic2; /* Magic number to detect structure corruption. */
-#endif
-};
-
-#ifndef NDEBUG
-#define WINMEM_MAGIC1 0x42b2830b
-#define WINMEM_MAGIC2 0xbd4d7cf4
-#endif
-
-static struct winMemData win_mem_data = {
-#ifndef NDEBUG
- WINMEM_MAGIC1,
-#endif
- NULL, FALSE
-#ifndef NDEBUG
- ,WINMEM_MAGIC2
-#endif
-};
-
-#ifndef NDEBUG
-#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
-#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
-#define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
-#else
-#define winMemAssertMagic()
-#endif
-
-#define winMemGetDataPtr() &win_mem_data
-#define winMemGetHeap() win_mem_data.hHeap
-#define winMemGetOwned() win_mem_data.bOwned
-
-static void *winMemMalloc(int nBytes);
-static void winMemFree(void *pPrior);
-static void *winMemRealloc(void *pPrior, int nBytes);
-static int winMemSize(void *p);
-static int winMemRoundup(int n);
-static int winMemInit(void *pAppData);
-static void winMemShutdown(void *pAppData);
-
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
-#endif /* SQLITE_WIN32_MALLOC */
-
-/*
-** The following variable is (normally) set once and never changes
-** thereafter. It records whether the operating system is Win9x
-** or WinNT.
-**
-** 0: Operating system unknown.
-** 1: Operating system is Win9x.
-** 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.
-*/
-#ifdef SQLITE_TEST
-SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
-#else
-static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
-#endif
-
-#ifndef SYSCALL
-# define SYSCALL sqlite3_syscall_ptr
-#endif
-
-/*
-** This function is not available on Windows CE or WinRT.
- */
-
-#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
-# define osAreFileApisANSI() 1
-#endif
-
-/*
-** Many system calls are accessed through pointer-to-functions so that
-** they may be overridden at runtime to facilitate fault injection during
-** testing and sandboxing. The following array holds the names and pointers
-** to all overrideable system calls.
-*/
-static struct win_syscall {
- const char *zName; /* Name of the system call */
- sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
- sqlite3_syscall_ptr pDefault; /* Default value */
-} aSyscall[] = {
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
- { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
-#else
- { "AreFileApisANSI", (SYSCALL)0, 0 },
-#endif
-
-#ifndef osAreFileApisANSI
-#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
-#endif
-
-#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
- { "CharLowerW", (SYSCALL)CharLowerW, 0 },
-#else
- { "CharLowerW", (SYSCALL)0, 0 },
-#endif
-
-#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
-
-#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
- { "CharUpperW", (SYSCALL)CharUpperW, 0 },
-#else
- { "CharUpperW", (SYSCALL)0, 0 },
-#endif
-
-#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
-
- { "CloseHandle", (SYSCALL)CloseHandle, 0 },
-
-#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "CreateFileA", (SYSCALL)CreateFileA, 0 },
-#else
- { "CreateFileA", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
- LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "CreateFileW", (SYSCALL)CreateFileW, 0 },
-#else
- { "CreateFileW", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
- LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
- (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
- SQLITE_WIN32_CREATEFILEMAPPINGA
- { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
-#else
- { "CreateFileMappingA", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
- DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
-
-#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
- (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
- { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
-#else
- { "CreateFileMappingW", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
- DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
-#else
- { "CreateMutexW", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
- LPCWSTR))aSyscall[8].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
-#else
- { "DeleteFileA", (SYSCALL)0, 0 },
-#endif
-
-#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
-#else
- { "DeleteFileW", (SYSCALL)0, 0 },
-#endif
-
-#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
-
-#if SQLITE_OS_WINCE
- { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
-#else
- { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
-#endif
-
-#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
- LPFILETIME))aSyscall[11].pCurrent)
-
-#if SQLITE_OS_WINCE
- { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
-#else
- { "FileTimeToSystemTime", (SYSCALL)0, 0 },
-#endif
-
-#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
- LPSYSTEMTIME))aSyscall[12].pCurrent)
-
- { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
-
-#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
-#else
- { "FormatMessageA", (SYSCALL)0, 0 },
-#endif
-
-#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
- DWORD,va_list*))aSyscall[14].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
-#else
- { "FormatMessageW", (SYSCALL)0, 0 },
-#endif
-
-#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
- DWORD,va_list*))aSyscall[15].pCurrent)
-
-#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
- { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
-#else
- { "FreeLibrary", (SYSCALL)0, 0 },
-#endif
-
-#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
-
- { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
-
-#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
-
-#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
- { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
-#else
- { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
- LPDWORD))aSyscall[18].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
-#else
- { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
- LPDWORD))aSyscall[19].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
-#else
- { "GetFileAttributesA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
-#else
- { "GetFileAttributesW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
-#else
- { "GetFileAttributesExW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
- LPVOID))aSyscall[22].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "GetFileSize", (SYSCALL)GetFileSize, 0 },
-#else
- { "GetFileSize", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
-
-#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
- { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
-#else
- { "GetFullPathNameA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
- LPSTR*))aSyscall[24].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
-#else
- { "GetFullPathNameW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
- LPWSTR*))aSyscall[25].pCurrent)
-
- { "GetLastError", (SYSCALL)GetLastError, 0 },
-
-#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
-
-#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
-#if SQLITE_OS_WINCE
- /* The GetProcAddressA() routine is only available on Windows CE. */
- { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
-#else
- /* All other Windows platforms expect GetProcAddress() to take
- ** an ANSI string regardless of the _UNICODE setting */
- { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
-#endif
-#else
- { "GetProcAddressA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
- LPCSTR))aSyscall[27].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
-#else
- { "GetSystemInfo", (SYSCALL)0, 0 },
-#endif
-
-#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
-
- { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
-
-#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
-
-#if !SQLITE_OS_WINCE
- { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
-#else
- { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
-#endif
-
-#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
- LPFILETIME))aSyscall[30].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
-#else
- { "GetTempPathA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
- { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
-#else
- { "GetTempPathW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "GetTickCount", (SYSCALL)GetTickCount, 0 },
-#else
- { "GetTickCount", (SYSCALL)0, 0 },
-#endif
-
-#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
- { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
-#else
- { "GetVersionExA", (SYSCALL)0, 0 },
-#endif
-
-#define osGetVersionExA ((BOOL(WINAPI*)( \
- LPOSVERSIONINFOA))aSyscall[34].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
- SQLITE_WIN32_GETVERSIONEX
- { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
-#else
- { "GetVersionExW", (SYSCALL)0, 0 },
-#endif
-
-#define osGetVersionExW ((BOOL(WINAPI*)( \
- LPOSVERSIONINFOW))aSyscall[35].pCurrent)
-
- { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
-
-#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
- SIZE_T))aSyscall[36].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "HeapCreate", (SYSCALL)HeapCreate, 0 },
-#else
- { "HeapCreate", (SYSCALL)0, 0 },
-#endif
-
-#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
- SIZE_T))aSyscall[37].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
-#else
- { "HeapDestroy", (SYSCALL)0, 0 },
-#endif
-
-#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
-
- { "HeapFree", (SYSCALL)HeapFree, 0 },
-
-#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
-
- { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
-
-#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
- SIZE_T))aSyscall[40].pCurrent)
-
- { "HeapSize", (SYSCALL)HeapSize, 0 },
-
-#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
- LPCVOID))aSyscall[41].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "HeapValidate", (SYSCALL)HeapValidate, 0 },
-#else
- { "HeapValidate", (SYSCALL)0, 0 },
-#endif
-
-#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
- LPCVOID))aSyscall[42].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
- { "HeapCompact", (SYSCALL)HeapCompact, 0 },
-#else
- { "HeapCompact", (SYSCALL)0, 0 },
-#endif
-
-#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
- { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
-#else
- { "LoadLibraryA", (SYSCALL)0, 0 },
-#endif
-
-#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
-
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
- !defined(SQLITE_OMIT_LOAD_EXTENSION)
- { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
-#else
- { "LoadLibraryW", (SYSCALL)0, 0 },
-#endif
-
-#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "LocalFree", (SYSCALL)LocalFree, 0 },
-#else
- { "LocalFree", (SYSCALL)0, 0 },
-#endif
-
-#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
- { "LockFile", (SYSCALL)LockFile, 0 },
-#else
- { "LockFile", (SYSCALL)0, 0 },
-#endif
-
-#ifndef osLockFile
-#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
- DWORD))aSyscall[47].pCurrent)
-#endif
-
-#if !SQLITE_OS_WINCE
- { "LockFileEx", (SYSCALL)LockFileEx, 0 },
-#else
- { "LockFileEx", (SYSCALL)0, 0 },
-#endif
-
-#ifndef osLockFileEx
-#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
- LPOVERLAPPED))aSyscall[48].pCurrent)
-#endif
-
-#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
- (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
- { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
-#else
- { "MapViewOfFile", (SYSCALL)0, 0 },
-#endif
-
-#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
- SIZE_T))aSyscall[49].pCurrent)
-
- { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
-
-#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
- int))aSyscall[50].pCurrent)
-
- { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
-
-#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
- LARGE_INTEGER*))aSyscall[51].pCurrent)
-
- { "ReadFile", (SYSCALL)ReadFile, 0 },
-
-#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
- LPOVERLAPPED))aSyscall[52].pCurrent)
-
- { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
-
-#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
-#else
- { "SetFilePointer", (SYSCALL)0, 0 },
-#endif
-
-#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
- DWORD))aSyscall[54].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "Sleep", (SYSCALL)Sleep, 0 },
-#else
- { "Sleep", (SYSCALL)0, 0 },
-#endif
-
-#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
-
- { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
-
-#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
- LPFILETIME))aSyscall[56].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
- { "UnlockFile", (SYSCALL)UnlockFile, 0 },
-#else
- { "UnlockFile", (SYSCALL)0, 0 },
-#endif
-
-#ifndef osUnlockFile
-#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
- DWORD))aSyscall[57].pCurrent)
-#endif
-
-#if !SQLITE_OS_WINCE
- { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
-#else
- { "UnlockFileEx", (SYSCALL)0, 0 },
-#endif
-
-#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
- LPOVERLAPPED))aSyscall[58].pCurrent)
-
-#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
- { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
-#else
- { "UnmapViewOfFile", (SYSCALL)0, 0 },
-#endif
-
-#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
-
- { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
-
-#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
- LPCSTR,LPBOOL))aSyscall[60].pCurrent)
-
- { "WriteFile", (SYSCALL)WriteFile, 0 },
-
-#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
- LPOVERLAPPED))aSyscall[61].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
-#else
- { "CreateEventExW", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
- DWORD,DWORD))aSyscall[62].pCurrent)
-
-#if !SQLITE_OS_WINRT
- { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
-#else
- { "WaitForSingleObject", (SYSCALL)0, 0 },
-#endif
-
-#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
- DWORD))aSyscall[63].pCurrent)
-
-#if !SQLITE_OS_WINCE
- { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
-#else
- { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
-#endif
-
-#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
- BOOL))aSyscall[64].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
-#else
- { "SetFilePointerEx", (SYSCALL)0, 0 },
-#endif
-
-#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
- PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
-#else
- { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
-#endif
-
-#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
- FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
-
-#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
- { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
-#else
- { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
-#endif
-
-#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
- SIZE_T))aSyscall[67].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "CreateFile2", (SYSCALL)CreateFile2, 0 },
-#else
- { "CreateFile2", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
- LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
-
-#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
- { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
-#else
- { "LoadPackagedLibrary", (SYSCALL)0, 0 },
-#endif
-
-#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
- DWORD))aSyscall[69].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
-#else
- { "GetTickCount64", (SYSCALL)0, 0 },
-#endif
-
-#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
-
-#if SQLITE_OS_WINRT
- { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
-#else
- { "GetNativeSystemInfo", (SYSCALL)0, 0 },
-#endif
-
-#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
- LPSYSTEM_INFO))aSyscall[71].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_ANSI)
- { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
-#else
- { "OutputDebugStringA", (SYSCALL)0, 0 },
-#endif
-
-#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
-#else
- { "OutputDebugStringW", (SYSCALL)0, 0 },
-#endif
-
-#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
-
- { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
-
-#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
-
-#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
- { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
-#else
- { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
-#endif
-
-#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
- LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
-
-/*
-** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
-** is really just a macro that uses a compiler intrinsic (e.g. x64).
-** So do not try to make this is into a redefinable interface.
-*/
-#if defined(InterlockedCompareExchange)
- { "InterlockedCompareExchange", (SYSCALL)0, 0 },
-
-#define osInterlockedCompareExchange InterlockedCompareExchange
-#else
- { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
-
-#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
- SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
-#endif /* defined(InterlockedCompareExchange) */
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
- { "UuidCreate", (SYSCALL)UuidCreate, 0 },
-#else
- { "UuidCreate", (SYSCALL)0, 0 },
-#endif
-
-#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
- { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
-#else
- { "UuidCreateSequential", (SYSCALL)0, 0 },
-#endif
-
-#define osUuidCreateSequential \
- ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
-
-#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
- { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
-#else
- { "FlushViewOfFile", (SYSCALL)0, 0 },
-#endif
-
-#define osFlushViewOfFile \
- ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
-
-}; /* End of the overrideable system calls */
-
-/*
-** This is the xSetSystemCall() method of sqlite3_vfs for all of the
-** "win32" VFSes. Return SQLITE_OK opon successfully updating the
-** system call pointer, or SQLITE_NOTFOUND if there is no configurable
-** system call named zName.
-*/
-static int winSetSystemCall(
- sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
- const char *zName, /* Name of system call to override */
- sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
-){
- unsigned int i;
- int rc = SQLITE_NOTFOUND;
-
- UNUSED_PARAMETER(pNotUsed);
- if( zName==0 ){
- /* If no zName is given, restore all system calls to their default
- ** settings and return NULL
- */
- rc = SQLITE_OK;
- for(i=0; i0 ){
- memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
- memcpy(zDbgBuf, zBuf, nMin);
- osOutputDebugStringA(zDbgBuf);
- }else{
- osOutputDebugStringA(zBuf);
- }
-#elif defined(SQLITE_WIN32_HAS_WIDE)
- memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
- if ( osMultiByteToWideChar(
- osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
- nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
- return;
- }
- osOutputDebugStringW((LPCWSTR)zDbgBuf);
-#else
- if( nMin>0 ){
- memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
- memcpy(zDbgBuf, zBuf, nMin);
- fprintf(stderr, "%s", zDbgBuf);
- }else{
- fprintf(stderr, "%s", zBuf);
- }
-#endif
-}
-
-/*
-** The following routine suspends the current thread for at least ms
-** milliseconds. This is equivalent to the Win32 Sleep() interface.
-*/
-#if SQLITE_OS_WINRT
-static HANDLE sleepObj = NULL;
-#endif
-
-SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
-#if SQLITE_OS_WINRT
- if ( sleepObj==NULL ){
- sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
- SYNCHRONIZE);
- }
- assert( sleepObj!=NULL );
- osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
-#else
- osSleep(milliseconds);
-#endif
-}
-
-#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
- SQLITE_THREADSAFE>0
-SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
- DWORD rc;
- while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
- TRUE))==WAIT_IO_COMPLETION ){}
- return rc;
-}
-#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_WIN32_GETVERSIONEX
-# define osIsNT() (1)
-#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
-# define osIsNT() (1)
-#elif !defined(SQLITE_WIN32_HAS_WIDE)
-# define osIsNT() (0)
-#else
-# define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
-#endif
-
-/*
-** This function determines if the machine is running a version of Windows
-** based on the NT kernel.
-*/
-SQLITE_API int sqlite3_win32_is_nt(void){
-#if SQLITE_OS_WINRT
- /*
- ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
- ** kernel.
- */
- return 1;
-#elif SQLITE_WIN32_GETVERSIONEX
- if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
-#if defined(SQLITE_WIN32_HAS_ANSI)
- OSVERSIONINFOA sInfo;
- sInfo.dwOSVersionInfoSize = sizeof(sInfo);
- osGetVersionExA(&sInfo);
- osInterlockedCompareExchange(&sqlite3_os_type,
- (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
-#elif defined(SQLITE_WIN32_HAS_WIDE)
- OSVERSIONINFOW sInfo;
- sInfo.dwOSVersionInfoSize = sizeof(sInfo);
- osGetVersionExW(&sInfo);
- osInterlockedCompareExchange(&sqlite3_os_type,
- (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
-#endif
- }
- return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
-#elif SQLITE_TEST
- return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
-#else
- /*
- ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
- ** deprecated are always assumed to be based on the NT kernel.
- */
- return 1;
-#endif
-}
-
-#ifdef SQLITE_WIN32_MALLOC
-/*
-** Allocate nBytes of memory.
-*/
-static void *winMemMalloc(int nBytes){
- HANDLE hHeap;
- void *p;
-
- winMemAssertMagic();
- hHeap = winMemGetHeap();
- assert( hHeap!=0 );
- assert( hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
-#endif
- assert( nBytes>=0 );
- p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
- if( !p ){
- sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
- nBytes, osGetLastError(), (void*)hHeap);
- }
- return p;
-}
-
-/*
-** Free memory.
-*/
-static void winMemFree(void *pPrior){
- HANDLE hHeap;
-
- winMemAssertMagic();
- hHeap = winMemGetHeap();
- assert( hHeap!=0 );
- assert( hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
-#endif
- if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
- if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
- sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
- pPrior, osGetLastError(), (void*)hHeap);
- }
-}
-
-/*
-** Change the size of an existing memory allocation
-*/
-static void *winMemRealloc(void *pPrior, int nBytes){
- HANDLE hHeap;
- void *p;
-
- winMemAssertMagic();
- hHeap = winMemGetHeap();
- assert( hHeap!=0 );
- assert( hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
-#endif
- assert( nBytes>=0 );
- if( !pPrior ){
- p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
- }else{
- p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
- }
- if( !p ){
- sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
- pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
- (void*)hHeap);
- }
- return p;
-}
-
-/*
-** Return the size of an outstanding allocation, in bytes.
-*/
-static int winMemSize(void *p){
- HANDLE hHeap;
- SIZE_T n;
-
- winMemAssertMagic();
- hHeap = winMemGetHeap();
- assert( hHeap!=0 );
- assert( hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
-#endif
- if( !p ) return 0;
- n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
- if( n==(SIZE_T)-1 ){
- sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
- p, osGetLastError(), (void*)hHeap);
- return 0;
- }
- return (int)n;
-}
-
-/*
-** Round up a request size to the next valid allocation size.
-*/
-static int winMemRoundup(int n){
- return n;
-}
-
-/*
-** Initialize this module.
-*/
-static int winMemInit(void *pAppData){
- winMemData *pWinMemData = (winMemData *)pAppData;
-
- if( !pWinMemData ) return SQLITE_ERROR;
- assert( pWinMemData->magic1==WINMEM_MAGIC1 );
- assert( pWinMemData->magic2==WINMEM_MAGIC2 );
-
-#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
- if( !pWinMemData->hHeap ){
- DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
- DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
- if( dwMaximumSize==0 ){
- dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
- }else if( dwInitialSize>dwMaximumSize ){
- dwInitialSize = dwMaximumSize;
- }
- pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
- dwInitialSize, dwMaximumSize);
- if( !pWinMemData->hHeap ){
- sqlite3_log(SQLITE_NOMEM,
- "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
- osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
- dwMaximumSize);
- return SQLITE_NOMEM_BKPT;
- }
- pWinMemData->bOwned = TRUE;
- assert( pWinMemData->bOwned );
- }
-#else
- pWinMemData->hHeap = osGetProcessHeap();
- if( !pWinMemData->hHeap ){
- sqlite3_log(SQLITE_NOMEM,
- "failed to GetProcessHeap (%lu)", osGetLastError());
- return SQLITE_NOMEM_BKPT;
- }
- pWinMemData->bOwned = FALSE;
- assert( !pWinMemData->bOwned );
-#endif
- assert( pWinMemData->hHeap!=0 );
- assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
-#endif
- return SQLITE_OK;
-}
-
-/*
-** Deinitialize this module.
-*/
-static void winMemShutdown(void *pAppData){
- winMemData *pWinMemData = (winMemData *)pAppData;
-
- if( !pWinMemData ) return;
- assert( pWinMemData->magic1==WINMEM_MAGIC1 );
- assert( pWinMemData->magic2==WINMEM_MAGIC2 );
-
- if( pWinMemData->hHeap ){
- assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
-#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
- assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
-#endif
- if( pWinMemData->bOwned ){
- if( !osHeapDestroy(pWinMemData->hHeap) ){
- sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
- osGetLastError(), (void*)pWinMemData->hHeap);
- }
- pWinMemData->bOwned = FALSE;
- }
- pWinMemData->hHeap = NULL;
- }
-}
-
-/*
-** Populate the low-level memory allocation function pointers in
-** sqlite3GlobalConfig.m with pointers to the routines in this file. The
-** arguments specify the block of memory to manage.
-**
-** This routine is only called by sqlite3_config(), and therefore
-** is not required to be threadsafe (it is not).
-*/
-SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
- static const sqlite3_mem_methods winMemMethods = {
- winMemMalloc,
- winMemFree,
- winMemRealloc,
- winMemSize,
- winMemRoundup,
- winMemInit,
- winMemShutdown,
- &win_mem_data
- };
- return &winMemMethods;
-}
-
-SQLITE_PRIVATE void sqlite3MemSetDefault(void){
- sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
-}
-#endif /* SQLITE_WIN32_MALLOC */
-
-/*
-** Convert a UTF-8 string to Microsoft Unicode.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static LPWSTR winUtf8ToUnicode(const char *zText){
- int nChar;
- LPWSTR zWideText;
-
- nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
- if( nChar==0 ){
- return 0;
- }
- zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
- if( zWideText==0 ){
- return 0;
- }
- nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
- nChar);
- if( nChar==0 ){
- sqlite3_free(zWideText);
- zWideText = 0;
- }
- return zWideText;
-}
-
-/*
-** Convert a Microsoft Unicode string to UTF-8.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static char *winUnicodeToUtf8(LPCWSTR zWideText){
- int nByte;
- char *zText;
-
- nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
- if( nByte == 0 ){
- return 0;
- }
- zText = sqlite3MallocZero( nByte );
- if( zText==0 ){
- return 0;
- }
- nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
- 0, 0);
- if( nByte == 0 ){
- sqlite3_free(zText);
- zText = 0;
- }
- return zText;
-}
-
-/*
-** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
-** code page.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
- int nByte;
- LPWSTR zMbcsText;
- int codepage = useAnsi ? CP_ACP : CP_OEMCP;
-
- nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
- 0)*sizeof(WCHAR);
- if( nByte==0 ){
- return 0;
- }
- zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
- if( zMbcsText==0 ){
- return 0;
- }
- nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
- nByte);
- if( nByte==0 ){
- sqlite3_free(zMbcsText);
- zMbcsText = 0;
- }
- return zMbcsText;
-}
-
-/*
-** Convert a Microsoft Unicode string to a multi-byte character string,
-** using the ANSI or OEM code page.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
- int nByte;
- char *zText;
- int codepage = useAnsi ? CP_ACP : CP_OEMCP;
-
- nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
- if( nByte == 0 ){
- return 0;
- }
- zText = sqlite3MallocZero( nByte );
- if( zText==0 ){
- return 0;
- }
- nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
- nByte, 0, 0);
- if( nByte == 0 ){
- sqlite3_free(zText);
- zText = 0;
- }
- return zText;
-}
-
-/*
-** Convert a multi-byte character string to UTF-8.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static char *winMbcsToUtf8(const char *zText, int useAnsi){
- char *zTextUtf8;
- LPWSTR zTmpWide;
-
- zTmpWide = winMbcsToUnicode(zText, useAnsi);
- if( zTmpWide==0 ){
- return 0;
- }
- zTextUtf8 = winUnicodeToUtf8(zTmpWide);
- sqlite3_free(zTmpWide);
- return zTextUtf8;
-}
-
-/*
-** Convert a UTF-8 string to a multi-byte character string.
-**
-** Space to hold the returned string is obtained from sqlite3_malloc().
-*/
-static char *winUtf8ToMbcs(const char *zText, int useAnsi){
- char *zTextMbcs;
- LPWSTR zTmpWide;
-
- zTmpWide = winUtf8ToUnicode(zText);
- if( zTmpWide==0 ){
- return 0;
- }
- zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
- sqlite3_free(zTmpWide);
- return zTextMbcs;
-}
-
-/*
-** This is a public wrapper for the winUtf8ToUnicode() function.
-*/
-SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winUtf8ToUnicode(zText);
-}
-
-/*
-** This is a public wrapper for the winUnicodeToUtf8() function.
-*/
-SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zWideText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winUnicodeToUtf8(zWideText);
-}
-
-/*
-** This is a public wrapper for the winMbcsToUtf8() function.
-*/
-SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winMbcsToUtf8(zText, osAreFileApisANSI());
-}
-
-/*
-** This is a public wrapper for the winMbcsToUtf8() function.
-*/
-SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winMbcsToUtf8(zText, useAnsi);
-}
-
-/*
-** This is a public wrapper for the winUtf8ToMbcs() function.
-*/
-SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winUtf8ToMbcs(zText, osAreFileApisANSI());
-}
-
-/*
-** This is a public wrapper for the winUtf8ToMbcs() function.
-*/
-SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !zText ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-#ifndef SQLITE_OMIT_AUTOINIT
- if( sqlite3_initialize() ) return 0;
-#endif
- return winUtf8ToMbcs(zText, useAnsi);
-}
-
-/*
-** This function is the same as sqlite3_win32_set_directory (below); however,
-** it accepts a UTF-8 string.
-*/
-SQLITE_API int sqlite3_win32_set_directory8(
- unsigned long type, /* Identifier for directory being set or reset */
- const char *zValue /* New value for directory being set or reset */
-){
- char **ppDirectory = 0;
-#ifndef SQLITE_OMIT_AUTOINIT
- int rc = sqlite3_initialize();
- if( rc ) return rc;
-#endif
- if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
- ppDirectory = &sqlite3_data_directory;
- }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
- ppDirectory = &sqlite3_temp_directory;
- }
- assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
- || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
- );
- assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
- if( ppDirectory ){
- char *zCopy = 0;
- if( zValue && zValue[0] ){
- zCopy = sqlite3_mprintf("%s", zValue);
- if ( zCopy==0 ){
- return SQLITE_NOMEM_BKPT;
- }
- }
- sqlite3_free(*ppDirectory);
- *ppDirectory = zCopy;
- return SQLITE_OK;
- }
- return SQLITE_ERROR;
-}
-
-/*
-** This function is the same as sqlite3_win32_set_directory (below); however,
-** it accepts a UTF-16 string.
-*/
-SQLITE_API int sqlite3_win32_set_directory16(
- unsigned long type, /* Identifier for directory being set or reset */
- const void *zValue /* New value for directory being set or reset */
-){
- int rc;
- char *zUtf8 = 0;
- if( zValue ){
- zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
- if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
- }
- rc = sqlite3_win32_set_directory8(type, zUtf8);
- if( zUtf8 ) sqlite3_free(zUtf8);
- return rc;
-}
-
-/*
-** This function sets the data directory or the temporary directory based on
-** the provided arguments. The type argument must be 1 in order to set the
-** data directory or 2 in order to set the temporary directory. The zValue
-** argument is the name of the directory to use. The return value will be
-** SQLITE_OK if successful.
-*/
-SQLITE_API int sqlite3_win32_set_directory(
- unsigned long type, /* Identifier for directory being set or reset */
- void *zValue /* New value for directory being set or reset */
-){
- return sqlite3_win32_set_directory16(type, zValue);
-}
-
-/*
-** The return value of winGetLastErrorMsg
-** is zero if the error message fits in the buffer, or non-zero
-** otherwise (if the message was truncated).
-*/
-static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
- /* FormatMessage returns 0 on failure. Otherwise it
- ** returns the number of TCHARs written to the output
- ** buffer, excluding the terminating null char.
- */
- DWORD dwLen = 0;
- char *zOut = 0;
-
- if( osIsNT() ){
-#if SQLITE_OS_WINRT
- WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
- dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- lastErrno,
- 0,
- zTempWide,
- SQLITE_WIN32_MAX_ERRMSG_CHARS,
- 0);
-#else
- LPWSTR zTempWide = NULL;
- dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- lastErrno,
- 0,
- (LPWSTR) &zTempWide,
- 0,
- 0);
-#endif
- if( dwLen > 0 ){
- /* allocate a buffer and convert to UTF8 */
- sqlite3BeginBenignMalloc();
- zOut = winUnicodeToUtf8(zTempWide);
- sqlite3EndBenignMalloc();
-#if !SQLITE_OS_WINRT
- /* free the system buffer allocated by FormatMessage */
- osLocalFree(zTempWide);
-#endif
- }
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- char *zTemp = NULL;
- dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- lastErrno,
- 0,
- (LPSTR) &zTemp,
- 0,
- 0);
- if( dwLen > 0 ){
- /* allocate a buffer and convert to UTF8 */
- sqlite3BeginBenignMalloc();
- zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
- sqlite3EndBenignMalloc();
- /* free the system buffer allocated by FormatMessage */
- osLocalFree(zTemp);
- }
- }
-#endif
- if( 0 == dwLen ){
- sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
- }else{
- /* copy a maximum of nBuf chars to output buffer */
- sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
- /* free the UTF8 buffer */
- sqlite3_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 associated file-system path, if any.
-*/
-#define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
-static int winLogErrorAtLine(
- int errcode, /* SQLite error code */
- DWORD lastErrno, /* Win32 last error */
- const char *zFunc, /* Name of OS function that failed */
- const char *zPath, /* File path associated with error */
- int iLine /* Source line number where error occurred */
-){
- char zMsg[500]; /* Human readable error text */
- int i; /* Loop counter */
-
- zMsg[0] = 0;
- winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
- assert( errcode!=SQLITE_OK );
- if( zPath==0 ) zPath = "";
- for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
- zMsg[i] = 0;
- sqlite3_log(errcode,
- "os_win.c:%d: (%lu) %s(%s) - %s",
- iLine, lastErrno, zFunc, zPath, zMsg
- );
-
- return errcode;
-}
-
-/*
-** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
-** will be retried following a locking error - probably caused by
-** antivirus software. Also the initial delay before the first retry.
-** The delay increases linearly with each retry.
-*/
-#ifndef SQLITE_WIN32_IOERR_RETRY
-# define SQLITE_WIN32_IOERR_RETRY 10
-#endif
-#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
-# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
-#endif
-static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
-static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
-
-/*
-** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
-** error code obtained via GetLastError() is eligible to be retried. It
-** must accept the error code DWORD as its only argument and should return
-** non-zero if the error code is transient in nature and the operation
-** responsible for generating the original error might succeed upon being
-** retried. The argument to this macro should be a variable.
-**
-** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
-** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
-** returns zero. The "winIoerrCanRetry2" macro is completely optional and
-** may be used to include additional error codes in the set that should
-** result in the failing I/O operation being retried by the caller. If
-** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
-** identical to those of the "winIoerrCanRetry1" macro.
-*/
-#if !defined(winIoerrCanRetry1)
-#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
- ((a)==ERROR_SHARING_VIOLATION) || \
- ((a)==ERROR_LOCK_VIOLATION) || \
- ((a)==ERROR_DEV_NOT_EXIST) || \
- ((a)==ERROR_NETNAME_DELETED) || \
- ((a)==ERROR_SEM_TIMEOUT) || \
- ((a)==ERROR_NETWORK_UNREACHABLE))
-#endif
-
-/*
-** If a ReadFile() or WriteFile() error occurs, invoke this routine
-** to see if it should be retried. Return TRUE to retry. Return FALSE
-** to give up with an error.
-*/
-static int winRetryIoerr(int *pnRetry, DWORD *pError){
- DWORD e = osGetLastError();
- if( *pnRetry>=winIoerrRetry ){
- if( pError ){
- *pError = e;
- }
- return 0;
- }
- if( winIoerrCanRetry1(e) ){
- sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
- ++*pnRetry;
- return 1;
- }
-#if defined(winIoerrCanRetry2)
- else if( winIoerrCanRetry2(e) ){
- sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
- ++*pnRetry;
- return 1;
- }
-#endif
- if( pError ){
- *pError = e;
- }
- return 0;
-}
-
-/*
-** Log a I/O error retry episode.
-*/
-static void winLogIoerr(int nRetry, int lineno){
- if( nRetry ){
- sqlite3_log(SQLITE_NOTICE,
- "delayed %dms for lock/sharing conflict at line %d",
- winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
- );
- }
-}
-
-/*
-** This #if does not rely on the SQLITE_OS_WINCE define because the
-** corresponding section in "date.c" cannot use it.
-*/
-#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
- (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
-/*
-** The MSVC CRT on Windows CE may not have a localtime() function.
-** So define 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);
- osFileTimeToLocalFileTime(&uTm,&lTm);
- osFileTimeToSystemTime(&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;
-}
-#endif
-
-#if SQLITE_OS_WINCE
-/*************************************************************************
-** This section contains code for WinCE only.
-*/
-#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 = osWaitForSingleObject(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 int winceCreateLock(const char *zFilename, winFile *pFile){
- LPWSTR zTok;
- LPWSTR zName;
- DWORD lastErrno;
- BOOL bLogged = FALSE;
- BOOL bInit = TRUE;
-
- zName = winUtf8ToUnicode(zFilename);
- if( zName==0 ){
- /* out of memory */
- return SQLITE_IOERR_NOMEM_BKPT;
- }
-
- /* Initialize the local lockdata */
- memset(&pFile->local, 0, sizeof(pFile->local));
-
- /* Replace the backslashes from the filename and lowercase it
- ** to derive a mutex name. */
- zTok = osCharLowerW(zName);
- for (;*zTok;zTok++){
- if (*zTok == '\\') *zTok = '_';
- }
-
- /* Create/open the named mutex */
- pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
- if (!pFile->hMutex){
- pFile->lastErrno = osGetLastError();
- sqlite3_free(zName);
- return winLogError(SQLITE_IOERR, pFile->lastErrno,
- "winceCreateLock1", zFilename);
- }
-
- /* 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.
- */
- osCharUpperW(zName);
- pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
- PAGE_READWRITE, 0, sizeof(winceLock),
- zName);
-
- /* Set a flag that indicates we're the first to create the memory so it
- ** must be zero-initialized */
- lastErrno = osGetLastError();
- if (lastErrno == ERROR_ALREADY_EXISTS){
- bInit = FALSE;
- }
-
- sqlite3_free(zName);
-
- /* If we succeeded in making the shared memory handle, map it. */
- if( pFile->hShared ){
- pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
- FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
- /* If mapping failed, close the shared memory handle and erase it */
- if( !pFile->shared ){
- pFile->lastErrno = osGetLastError();
- winLogError(SQLITE_IOERR, pFile->lastErrno,
- "winceCreateLock2", zFilename);
- bLogged = TRUE;
- osCloseHandle(pFile->hShared);
- pFile->hShared = NULL;
- }
- }
-
- /* If shared memory could not be created, then close the mutex and fail */
- if( pFile->hShared==NULL ){
- if( !bLogged ){
- pFile->lastErrno = lastErrno;
- winLogError(SQLITE_IOERR, pFile->lastErrno,
- "winceCreateLock3", zFilename);
- bLogged = TRUE;
- }
- winceMutexRelease(pFile->hMutex);
- osCloseHandle(pFile->hMutex);
- pFile->hMutex = NULL;
- return SQLITE_IOERR;
- }
-
- /* Initialize the shared memory if we're supposed to */
- if( bInit ){
- memset(pFile->shared, 0, sizeof(winceLock));
- }
-
- winceMutexRelease(pFile->hMutex);
- return SQLITE_OK;
-}
-
-/*
-** Destroy the part of winFile that deals with wince locks
-*/
-static void winceDestroyLock(winFile *pFile){
- if (pFile->hMutex){
- /* Acquire the mutex */
- winceMutexAcquire(pFile->hMutex);
-
- /* The following blocks should probably 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 */
- osUnmapViewOfFile(pFile->shared);
- osCloseHandle(pFile->hShared);
-
- /* Done with the mutex */
- winceMutexRelease(pFile->hMutex);
- osCloseHandle(pFile->hMutex);
- pFile->hMutex = NULL;
- }
-}
-
-/*
-** An implementation of the LockFile() API of Windows for CE
-*/
-static BOOL winceLockFile(
- LPHANDLE 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 CE
-*/
-static BOOL winceUnlockFile(
- LPHANDLE 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){
- 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){
- 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;
-}
-/*
-** End of the special code for wince
-*****************************************************************************/
-#endif /* SQLITE_OS_WINCE */
-
-/*
-** Lock a file region.
-*/
-static BOOL winLockFile(
- LPHANDLE phFile,
- DWORD flags,
- DWORD offsetLow,
- DWORD offsetHigh,
- DWORD numBytesLow,
- DWORD numBytesHigh
-){
-#if SQLITE_OS_WINCE
- /*
- ** NOTE: Windows CE is handled differently here due its lack of the Win32
- ** API LockFile.
- */
- return winceLockFile(phFile, offsetLow, offsetHigh,
- numBytesLow, numBytesHigh);
-#else
- if( osIsNT() ){
- OVERLAPPED ovlp;
- memset(&ovlp, 0, sizeof(OVERLAPPED));
- ovlp.Offset = offsetLow;
- ovlp.OffsetHigh = offsetHigh;
- return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
- }else{
- return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
- numBytesHigh);
- }
-#endif
-}
-
-/*
-** Unlock a file region.
- */
-static BOOL winUnlockFile(
- LPHANDLE phFile,
- DWORD offsetLow,
- DWORD offsetHigh,
- DWORD numBytesLow,
- DWORD numBytesHigh
-){
-#if SQLITE_OS_WINCE
- /*
- ** NOTE: Windows CE is handled differently here due its lack of the Win32
- ** API UnlockFile.
- */
- return winceUnlockFile(phFile, offsetLow, offsetHigh,
- numBytesLow, numBytesHigh);
-#else
- if( osIsNT() ){
- OVERLAPPED ovlp;
- memset(&ovlp, 0, sizeof(OVERLAPPED));
- ovlp.Offset = offsetLow;
- ovlp.OffsetHigh = offsetHigh;
- return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
- }else{
- return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
- numBytesHigh);
- }
-#endif
-}
-
-/*****************************************************************************
-** The next group of routines implement the I/O methods specified
-** by the sqlite3_io_methods object.
-******************************************************************************/
-
-/*
-** Some Microsoft compilers lack this definition.
-*/
-#ifndef INVALID_SET_FILE_POINTER
-# define INVALID_SET_FILE_POINTER ((DWORD)-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 winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
-#if !SQLITE_OS_WINRT
- LONG upperBits; /* Most sig. 32 bits of new offset */
- LONG lowerBits; /* Least sig. 32 bits of new offset */
- DWORD dwRet; /* Value returned by SetFilePointer() */
- DWORD lastErrno; /* Value returned by GetLastError() */
-
- OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
-
- 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 occurred, it is also necessary to call
- ** GetLastError().
- */
- dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
-
- if( (dwRet==INVALID_SET_FILE_POINTER
- && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
- pFile->lastErrno = lastErrno;
- winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
- "winSeekFile", pFile->zPath);
- OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
- return 1;
- }
-
- OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
- return 0;
-#else
- /*
- ** Same as above, except that this implementation works for WinRT.
- */
-
- LARGE_INTEGER x; /* The new offset */
- BOOL bRet; /* Value returned by SetFilePointerEx() */
-
- x.QuadPart = iOffset;
- bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
-
- if(!bRet){
- pFile->lastErrno = osGetLastError();
- winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
- "winSeekFile", pFile->zPath);
- OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
- return 1;
- }
-
- OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
- return 0;
-#endif
-}
-
-#if SQLITE_MAX_MMAP_SIZE>0
-/* Forward references to VFS helper methods used for memory mapped files */
-static int winMapfile(winFile*, sqlite3_int64);
-static int winUnmapfile(winFile*);
-#endif
-
-/*
-** 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.
-*/
-#define MX_CLOSE_ATTEMPT 3
-static int winClose(sqlite3_file *id){
- int rc, cnt = 0;
- winFile *pFile = (winFile*)id;
-
- assert( id!=0 );
-#ifndef SQLITE_OMIT_WAL
- assert( pFile->pShm==0 );
-#endif
- assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
- OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
- osGetCurrentProcessId(), pFile, pFile->h));
-
-#if SQLITE_MAX_MMAP_SIZE>0
- winUnmapfile(pFile);
-#endif
-
- do{
- rc = osCloseHandle(pFile->h);
- /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
- }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
-#if SQLITE_OS_WINCE
-#define WINCE_DELETION_ATTEMPTS 3
- {
- winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
- if( pAppData==NULL || !pAppData->bNoLock ){
- winceDestroyLock(pFile);
- }
- }
- if( pFile->zDeleteOnClose ){
- int cnt = 0;
- while(
- osDeleteFileW(pFile->zDeleteOnClose)==0
- && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
- && cnt++ < WINCE_DELETION_ATTEMPTS
- ){
- sqlite3_win32_sleep(100); /* Wait a little before trying again */
- }
- sqlite3_free(pFile->zDeleteOnClose);
- }
-#endif
- if( rc ){
- pFile->h = NULL;
- }
- OpenCounter(-1);
- OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
- osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
- return rc ? SQLITE_OK
- : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
- "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 */
- void *pBuf, /* Write content into this buffer */
- int amt, /* Number of bytes to read */
- sqlite3_int64 offset /* Begin reading at this offset */
-){
-#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
- OVERLAPPED overlapped; /* The offset for ReadFile. */
-#endif
- winFile *pFile = (winFile*)id; /* file handle */
- DWORD nRead; /* Number of bytes actually read from file */
- int nRetry = 0; /* Number of retrys */
-
- assert( id!=0 );
- assert( amt>0 );
- assert( offset>=0 );
- SimulateIOError(return SQLITE_IOERR_READ);
- OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
- "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
- pFile->h, pBuf, amt, offset, pFile->locktype));
-
-#if SQLITE_MAX_MMAP_SIZE>0
- /* Deal with as much of this read request as possible by transfering
- ** data from the memory mapping using memcpy(). */
- if( offsetmmapSize ){
- if( offset+amt <= pFile->mmapSize ){
- memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
- OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_OK;
- }else{
- int nCopy = (int)(pFile->mmapSize - offset);
- memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
- pBuf = &((u8 *)pBuf)[nCopy];
- amt -= nCopy;
- offset += nCopy;
- }
- }
-#endif
-
-#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
- if( winSeekFile(pFile, offset) ){
- OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_FULL;
- }
- while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
-#else
- memset(&overlapped, 0, sizeof(OVERLAPPED));
- overlapped.Offset = (LONG)(offset & 0xffffffff);
- overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
- while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
- osGetLastError()!=ERROR_HANDLE_EOF ){
-#endif
- DWORD lastErrno;
- if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
- pFile->lastErrno = lastErrno;
- OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
- "winRead", pFile->zPath);
- }
- winLogIoerr(nRetry, __LINE__);
- if( nRead<(DWORD)amt ){
- /* Unread parts of the buffer must be zero-filled */
- memset(&((char*)pBuf)[nRead], 0, amt-nRead);
- OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_IOERR_SHORT_READ;
- }
-
- OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- 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 */
- const void *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 = 0; /* True if error has occurred, else false */
- winFile *pFile = (winFile*)id; /* File handle */
- int nRetry = 0; /* Number of retries */
-
- assert( amt>0 );
- assert( pFile );
- SimulateIOError(return SQLITE_IOERR_WRITE);
- SimulateDiskfullError(return SQLITE_FULL);
-
- OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
- "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
- pFile->h, pBuf, amt, offset, pFile->locktype));
-
-#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
- /* Deal with as much of this write request as possible by transfering
- ** data from the memory mapping using memcpy(). */
- if( offsetmmapSize ){
- if( offset+amt <= pFile->mmapSize ){
- memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
- OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_OK;
- }else{
- int nCopy = (int)(pFile->mmapSize - offset);
- memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
- pBuf = &((u8 *)pBuf)[nCopy];
- amt -= nCopy;
- offset += nCopy;
- }
- }
-#endif
-
-#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
- rc = winSeekFile(pFile, offset);
- if( rc==0 ){
-#else
- {
-#endif
-#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
- OVERLAPPED overlapped; /* The offset for WriteFile. */
-#endif
- 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 */
- DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
-
-#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
- memset(&overlapped, 0, sizeof(OVERLAPPED));
- overlapped.Offset = (LONG)(offset & 0xffffffff);
- overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
-#endif
-
- while( nRem>0 ){
-#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
- if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
-#else
- if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
-#endif
- if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
- break;
- }
- assert( nWrite==0 || nWrite<=(DWORD)nRem );
- if( nWrite==0 || nWrite>(DWORD)nRem ){
- lastErrno = osGetLastError();
- break;
- }
-#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
- offset += nWrite;
- overlapped.Offset = (LONG)(offset & 0xffffffff);
- overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
-#endif
- aRem += nWrite;
- nRem -= nWrite;
- }
- if( nRem>0 ){
- pFile->lastErrno = lastErrno;
- rc = 1;
- }
- }
-
- if( rc ){
- if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
- || ( pFile->lastErrno==ERROR_DISK_FULL )){
- OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return winLogError(SQLITE_FULL, pFile->lastErrno,
- "winWrite1", pFile->zPath);
- }
- OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
- "winWrite2", pFile->zPath);
- }else{
- winLogIoerr(nRetry, __LINE__);
- }
- OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_OK;
-}
-
-/*
-** Truncate an open file to a specified size
-*/
-static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
- winFile *pFile = (winFile*)id; /* File handle object */
- int rc = SQLITE_OK; /* Return code for this function */
- DWORD lastErrno;
-#if SQLITE_MAX_MMAP_SIZE>0
- sqlite3_int64 oldMmapSize;
- if( pFile->nFetchOut>0 ){
- /* File truncation is a no-op if there are outstanding memory mapped
- ** pages. This is because truncating the file means temporarily unmapping
- ** the file, and that might delete memory out from under existing cursors.
- **
- ** This can result in incremental vacuum not truncating the file,
- ** if there is an active read cursor when the incremental vacuum occurs.
- ** No real harm comes of this - the database file is not corrupted,
- ** though some folks might complain that the file is bigger than it
- ** needs to be.
- **
- ** The only feasible work-around is to defer the truncation until after
- ** all references to memory-mapped content are closed. That is doable,
- ** but involves adding a few branches in the common write code path which
- ** could slow down normal operations slightly. Hence, we have decided for
- ** now to simply make trancations a no-op if there are pending reads. We
- ** can maybe revisit this decision in the future.
- */
- return SQLITE_OK;
- }
-#endif
-
- assert( pFile );
- SimulateIOError(return SQLITE_IOERR_TRUNCATE);
- OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
- osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
-
- /* 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;
- }
-
-#if SQLITE_MAX_MMAP_SIZE>0
- if( pFile->pMapRegion ){
- oldMmapSize = pFile->mmapSize;
- }else{
- oldMmapSize = 0;
- }
- winUnmapfile(pFile);
-#endif
-
- /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
- if( winSeekFile(pFile, nByte) ){
- rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
- "winTruncate1", pFile->zPath);
- }else if( 0==osSetEndOfFile(pFile->h) &&
- ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
- pFile->lastErrno = lastErrno;
- rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
- "winTruncate2", pFile->zPath);
- }
-
-#if SQLITE_MAX_MMAP_SIZE>0
- if( rc==SQLITE_OK && oldMmapSize>0 ){
- if( oldMmapSize>nByte ){
- winMapfile(pFile, -1);
- }else{
- winMapfile(pFile, oldMmapSize);
- }
- }
-#endif
-
- OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
- osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
- return rc;
-}
-
-#ifdef 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.
-*/
-SQLITE_API int sqlite3_sync_count = 0;
-SQLITE_API int sqlite3_fullsync_count = 0;
-#endif
-
-/*
-** Make sure all writes to a particular file are committed to disk.
-*/
-static int winSync(sqlite3_file *id, int flags){
-#ifndef SQLITE_NO_SYNC
- /*
- ** Used only when SQLITE_NO_SYNC is not defined.
- */
- BOOL rc;
-#endif
-#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
- defined(SQLITE_HAVE_OS_TRACE)
- /*
- ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
- ** OSTRACE() macros.
- */
- winFile *pFile = (winFile*)id;
-#else
- UNUSED_PARAMETER(id);
-#endif
-
- assert( pFile );
- /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
- assert((flags&0x0F)==SQLITE_SYNC_NORMAL
- || (flags&0x0F)==SQLITE_SYNC_FULL
- );
-
- /* Unix cannot, but some systems may return SQLITE_FULL from here. This
- ** line is to test that doing so does not cause any problems.
- */
- SimulateDiskfullError( return SQLITE_FULL );
-
- OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
- osGetCurrentProcessId(), pFile, pFile->h, flags,
- pFile->locktype));
-
-#ifndef SQLITE_TEST
- UNUSED_PARAMETER(flags);
-#else
- if( (flags&0x0F)==SQLITE_SYNC_FULL ){
- sqlite3_fullsync_count++;
- }
- sqlite3_sync_count++;
-#endif
-
- /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
- ** no-op
- */
-#ifdef SQLITE_NO_SYNC
- OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_OK;
-#else
-#if SQLITE_MAX_MMAP_SIZE>0
- if( pFile->pMapRegion ){
- if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
- OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
- "rc=SQLITE_OK\n", osGetCurrentProcessId(),
- pFile, pFile->pMapRegion));
- }else{
- pFile->lastErrno = osGetLastError();
- OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
- "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
- pFile, pFile->pMapRegion));
- return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
- "winSync1", pFile->zPath);
- }
- }
-#endif
- rc = osFlushFileBuffers(pFile->h);
- SimulateIOError( rc=FALSE );
- if( rc ){
- OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return SQLITE_OK;
- }else{
- pFile->lastErrno = osGetLastError();
- OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
- osGetCurrentProcessId(), pFile, pFile->h));
- return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
- "winSync2", pFile->zPath);
- }
-#endif
-}
-
-/*
-** Determine the current size of a file in bytes
-*/
-static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
- winFile *pFile = (winFile*)id;
- int rc = SQLITE_OK;
-
- assert( id!=0 );
- assert( pSize!=0 );
- SimulateIOError(return SQLITE_IOERR_FSTAT);
- OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
-
-#if SQLITE_OS_WINRT
- {
- FILE_STANDARD_INFO info;
- if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
- &info, sizeof(info)) ){
- *pSize = info.EndOfFile.QuadPart;
- }else{
- pFile->lastErrno = osGetLastError();
- rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
- "winFileSize", pFile->zPath);
- }
- }
-#else
- {
- DWORD upperBits;
- DWORD lowerBits;
- DWORD lastErrno;
-
- lowerBits = osGetFileSize(pFile->h, &upperBits);
- *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
- if( (lowerBits == INVALID_FILE_SIZE)
- && ((lastErrno = osGetLastError())!=NO_ERROR) ){
- pFile->lastErrno = lastErrno;
- rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
- "winFileSize", pFile->zPath);
- }
- }
-#endif
- OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
- pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
- return rc;
-}
-
-/*
-** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
-*/
-#ifndef LOCKFILE_FAIL_IMMEDIATELY
-# define LOCKFILE_FAIL_IMMEDIATELY 1
-#endif
-
-#ifndef LOCKFILE_EXCLUSIVE_LOCK
-# define LOCKFILE_EXCLUSIVE_LOCK 2
-#endif
-
-/*
-** Historically, SQLite has used both the LockFile and LockFileEx functions.
-** When the LockFile function was used, it was always expected to fail
-** immediately if the lock could not be obtained. Also, it always expected to
-** obtain an exclusive lock. These flags are used with the LockFileEx function
-** and reflect those expectations; therefore, they should not be changed.
-*/
-#ifndef SQLITE_LOCKFILE_FLAGS
-# define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
- LOCKFILE_EXCLUSIVE_LOCK)
-#endif
-
-/*
-** Currently, SQLite never calls the LockFileEx function without wanting the
-** call to fail immediately if the lock cannot be obtained.
-*/
-#ifndef SQLITE_LOCKFILEEX_FLAGS
-# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
-#endif
-
-/*
-** Acquire a reader lock.
-** Different API routines are called depending on whether or not this
-** is Win9x or WinNT.
-*/
-static int winGetReadLock(winFile *pFile){
- int res;
- OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
- if( osIsNT() ){
-#if SQLITE_OS_WINCE
- /*
- ** NOTE: Windows CE is handled differently here due its lack of the Win32
- ** API LockFileEx.
- */
- res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
-#else
- res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
- SHARED_SIZE, 0);
-#endif
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- int lk;
- sqlite3_randomness(sizeof(lk), &lk);
- pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
- res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
- SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
- }
-#endif
- if( res == 0 ){
- pFile->lastErrno = osGetLastError();
- /* No need to log a failure to lock */
- }
- OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
- return res;
-}
-
-/*
-** Undo a readlock
-*/
-static int winUnlockReadLock(winFile *pFile){
- int res;
- DWORD lastErrno;
- OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
- if( osIsNT() ){
- res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
- }
-#endif
- if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
- pFile->lastErrno = lastErrno;
- winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
- "winUnlockReadLock", pFile->zPath);
- }
- OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
- 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 */
- int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
- winFile *pFile = (winFile*)id;
- DWORD lastErrno = NO_ERROR;
-
- assert( id!=0 );
- OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
- pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
-
- /* 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 ){
- OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
-
- /* Do not allow any kind of write-lock on a read-only database
- */
- if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
- return SQLITE_IOERR_LOCK;
- }
-
- /* Make sure the locking sequence is correct
- */
- assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
- assert( locktype!=PENDING_LOCK );
- 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;
- while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
- PENDING_BYTE, 0, 1, 0))==0 ){
- /* Try 3 times to get the pending lock. This is needed to work
- ** around problems caused by indexing and/or anti-virus software on
- ** Windows systems.
- ** If you are using this code as a model for alternative VFSes, do not
- ** copy this retry logic. It is a hack intended for Windows only.
- */
- lastErrno = osGetLastError();
- OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
- pFile->h, cnt, res));
- if( lastErrno==ERROR_INVALID_HANDLE ){
- pFile->lastErrno = lastErrno;
- rc = SQLITE_IOERR_LOCK;
- OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
- pFile->h, cnt, sqlite3ErrName(rc)));
- return rc;
- }
- if( cnt ) sqlite3_win32_sleep(1);
- }
- gotPendingLock = res;
- if( !res ){
- lastErrno = osGetLastError();
- }
- }
-
- /* Acquire a shared lock
- */
- if( locktype==SHARED_LOCK && res ){
- assert( pFile->locktype==NO_LOCK );
- res = winGetReadLock(pFile);
- if( res ){
- newLocktype = SHARED_LOCK;
- }else{
- lastErrno = osGetLastError();
- }
- }
-
- /* Acquire a RESERVED lock
- */
- if( locktype==RESERVED_LOCK && res ){
- assert( pFile->locktype==SHARED_LOCK );
- res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
- if( res ){
- newLocktype = RESERVED_LOCK;
- }else{
- lastErrno = osGetLastError();
- }
- }
-
- /* Acquire a PENDING lock
- */
- if( locktype==EXCLUSIVE_LOCK && res ){
- newLocktype = PENDING_LOCK;
- gotPendingLock = 0;
- }
-
- /* Acquire an EXCLUSIVE lock
- */
- if( locktype==EXCLUSIVE_LOCK && res ){
- assert( pFile->locktype>=SHARED_LOCK );
- res = winUnlockReadLock(pFile);
- res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
- SHARED_SIZE, 0);
- if( res ){
- newLocktype = EXCLUSIVE_LOCK;
- }else{
- lastErrno = osGetLastError();
- winGetReadLock(pFile);
- }
- }
-
- /* If we are holding a PENDING lock that ought to be released, then
- ** release it now.
- */
- if( gotPendingLock && locktype==SHARED_LOCK ){
- winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
- }
-
- /* Update the state of the lock has held in the file descriptor then
- ** return the appropriate result code.
- */
- if( res ){
- rc = SQLITE_OK;
- }else{
- pFile->lastErrno = lastErrno;
- rc = SQLITE_BUSY;
- OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
- pFile->h, locktype, newLocktype));
- }
- pFile->locktype = (u8)newLocktype;
- OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
- pFile->h, pFile->locktype, sqlite3ErrName(rc)));
- 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, int *pResOut){
- int res;
- winFile *pFile = (winFile*)id;
-
- SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
- OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
-
- assert( id!=0 );
- if( pFile->locktype>=RESERVED_LOCK ){
- res = 1;
- OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
- }else{
- res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
- if( res ){
- winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
- }
- res = !res;
- OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
- }
- *pResOut = res;
- OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
- pFile->h, pResOut, *pResOut));
- 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;
- winFile *pFile = (winFile*)id;
- int rc = SQLITE_OK;
- assert( pFile!=0 );
- assert( locktype<=SHARED_LOCK );
- OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
- pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
- type = pFile->locktype;
- if( type>=EXCLUSIVE_LOCK ){
- winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
- if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
- /* This should never happen. We should always be able to
- ** reacquire the read lock */
- rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
- "winUnlock", pFile->zPath);
- }
- }
- if( type>=RESERVED_LOCK ){
- winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
- }
- if( locktype==NO_LOCK && type>=SHARED_LOCK ){
- winUnlockReadLock(pFile);
- }
- if( type>=PENDING_LOCK ){
- winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
- }
- pFile->locktype = (u8)locktype;
- OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
- pFile->h, pFile->locktype, sqlite3ErrName(rc)));
- return rc;
-}
-
-/******************************************************************************
-****************************** No-op Locking **********************************
-**
-** Of the various locking implementations available, this is by far the
-** simplest: locking is ignored. No attempt is made to lock the database
-** file for reading or writing.
-**
-** This locking mode is appropriate for use on read-only databases
-** (ex: databases that are burned into CD-ROM, for example.) It can
-** also be used if the application employs some external mechanism to
-** prevent simultaneous access of the same database by two or more
-** database connections. But there is a serious risk of database
-** corruption if this locking mode is used in situations where multiple
-** database connections are accessing the same database file at the same
-** time and one or more of those connections are writing.
-*/
-
-static int winNolockLock(sqlite3_file *id, int locktype){
- UNUSED_PARAMETER(id);
- UNUSED_PARAMETER(locktype);
- return SQLITE_OK;
-}
-
-static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
- UNUSED_PARAMETER(id);
- UNUSED_PARAMETER(pResOut);
- return SQLITE_OK;
-}
-
-static int winNolockUnlock(sqlite3_file *id, int locktype){
- UNUSED_PARAMETER(id);
- UNUSED_PARAMETER(locktype);
- return SQLITE_OK;
-}
-
-/******************* End of the no-op lock implementation *********************
-******************************************************************************/
-
-/*
-** If *pArg is initially negative then this is a query. Set *pArg to
-** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
-**
-** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
-*/
-static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
- if( *pArg<0 ){
- *pArg = (pFile->ctrlFlags & mask)!=0;
- }else if( (*pArg)==0 ){
- pFile->ctrlFlags &= ~mask;
- }else{
- pFile->ctrlFlags |= mask;
- }
-}
-
-/* Forward references to VFS helper methods used for temporary files */
-static int winGetTempname(sqlite3_vfs *, char **);
-static int winIsDir(const void *);
-static BOOL winIsDriveLetterAndColon(const char *);
-
-/*
-** Control and query of the open file handle.
-*/
-static int winFileControl(sqlite3_file *id, int op, void *pArg){
- winFile *pFile = (winFile*)id;
- OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
- switch( op ){
- case SQLITE_FCNTL_LOCKSTATE: {
- *(int*)pArg = pFile->locktype;
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_LAST_ERRNO: {
- *(int*)pArg = (int)pFile->lastErrno;
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_CHUNK_SIZE: {
- pFile->szChunk = *(int *)pArg;
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_SIZE_HINT: {
- if( pFile->szChunk>0 ){
- sqlite3_int64 oldSz;
- int rc = winFileSize(id, &oldSz);
- if( rc==SQLITE_OK ){
- sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
- if( newSz>oldSz ){
- SimulateIOErrorBenign(1);
- rc = winTruncate(id, newSz);
- SimulateIOErrorBenign(0);
- }
- }
- OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
- return rc;
- }
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_PERSIST_WAL: {
- winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
- winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_VFSNAME: {
- *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_WIN32_AV_RETRY: {
- int *a = (int*)pArg;
- if( a[0]>0 ){
- winIoerrRetry = a[0];
- }else{
- a[0] = winIoerrRetry;
- }
- if( a[1]>0 ){
- winIoerrRetryDelay = a[1];
- }else{
- a[1] = winIoerrRetryDelay;
- }
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
- case SQLITE_FCNTL_WIN32_GET_HANDLE: {
- LPHANDLE phFile = (LPHANDLE)pArg;
- *phFile = pFile->h;
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
- return SQLITE_OK;
- }
-#ifdef SQLITE_TEST
- case SQLITE_FCNTL_WIN32_SET_HANDLE: {
- LPHANDLE phFile = (LPHANDLE)pArg;
- HANDLE hOldFile = pFile->h;
- pFile->h = *phFile;
- *phFile = hOldFile;
- OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
- hOldFile, pFile->h));
- return SQLITE_OK;
- }
-#endif
- case SQLITE_FCNTL_TEMPFILENAME: {
- char *zTFile = 0;
- int rc = winGetTempname(pFile->pVfs, &zTFile);
- if( rc==SQLITE_OK ){
- *(char**)pArg = zTFile;
- }
- OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
- return rc;
- }
-#if SQLITE_MAX_MMAP_SIZE>0
- case SQLITE_FCNTL_MMAP_SIZE: {
- i64 newLimit = *(i64*)pArg;
- int rc = SQLITE_OK;
- if( newLimit>sqlite3GlobalConfig.mxMmap ){
- newLimit = sqlite3GlobalConfig.mxMmap;
- }
-
- /* The value of newLimit may be eventually cast to (SIZE_T) and passed
- ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
- ** least a 64-bit type. */
- if( newLimit>0 && sizeof(SIZE_T)<8 ){
- newLimit = (newLimit & 0x7FFFFFFF);
- }
-
- *(i64*)pArg = pFile->mmapSizeMax;
- if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
- pFile->mmapSizeMax = newLimit;
- if( pFile->mmapSize>0 ){
- winUnmapfile(pFile);
- rc = winMapfile(pFile, -1);
- }
- }
- OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
- return rc;
- }
-#endif
- }
- OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
- 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){
- (void)id;
- return SQLITE_DEFAULT_SECTOR_SIZE;
-}
-
-/*
-** Return a vector of device characteristics.
-*/
-static int winDeviceCharacteristics(sqlite3_file *id){
- winFile *p = (winFile*)id;
- return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
- ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
-}
-
-/*
-** 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.
-*/
-static SYSTEM_INFO winSysInfo;
-
-#ifndef SQLITE_OMIT_WAL
-
-/*
-** 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 assert() that the global mutex
-** is held when required. This function is only used as part of assert()
-** statements. e.g.
-**
-** winShmEnterMutex()
-** assert( winShmMutexHeld() );
-** winShmLeaveMutex()
-*/
-static sqlite3_mutex *winBigLock = 0;
-static void winShmEnterMutex(void){
- sqlite3_mutex_enter(winBigLock);
-}
-static void winShmLeaveMutex(void){
- sqlite3_mutex_leave(winBigLock);
-}
-#ifndef NDEBUG
-static int winShmMutexHeld(void) {
- return sqlite3_mutex_held(winBigLock);
-}
-#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 */
- char *zFilename; /* Name of the file */
- winFile hFile; /* File handle from winOpen */
-
- int szRegion; /* Size of shared-memory regions */
- int nRegion; /* Size of array apRegion */
- u8 isReadonly; /* True if read-only */
- u8 isUnlocked; /* True if no DMS lock held */
-
- 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 defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
- 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 defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
- 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 WINSHM_UNLCK 1
-#define WINSHM_RDLCK 2
-#define WINSHM_WRLCK 3
-static int winShmSystemLock(
- winShmNode *pFile, /* Apply locks to this open shared-memory segment */
- int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
- int ofst, /* Offset to first byte to be locked/unlocked */
- int nByte /* Number of bytes to lock or unlock */
-){
- int rc = 0; /* Result code form Lock/UnlockFileEx() */
-
- /* Access to the winShmNode object is serialized by the caller */
- assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
-
- OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
- pFile->hFile.h, lockType, ofst, nByte));
-
- /* Release/Acquire the system-level lock */
- if( lockType==WINSHM_UNLCK ){
- rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
- }else{
- /* Initialize the locking parameters */
- DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
- if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
- rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
- }
-
- if( rc!= 0 ){
- rc = SQLITE_OK;
- }else{
- pFile->lastErrno = osGetLastError();
- rc = SQLITE_BUSY;
- }
-
- OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
- pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
- "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
-
- 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;
- assert( winShmMutexHeld() );
- OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
- osGetCurrentProcessId(), deleteFlag));
- 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++){
- BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
- OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
- osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
- UNUSED_VARIABLE_VALUE(bRc);
- bRc = osCloseHandle(p->aRegion[i].hMap);
- OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
- osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
- UNUSED_VARIABLE_VALUE(bRc);
- }
- if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
- SimulateIOErrorBenign(1);
- winClose((sqlite3_file *)&p->hFile);
- SimulateIOErrorBenign(0);
- }
- if( deleteFlag ){
- SimulateIOErrorBenign(1);
- sqlite3BeginBenignMalloc();
- winDelete(pVfs, p->zFilename, 0);
- sqlite3EndBenignMalloc();
- SimulateIOErrorBenign(0);
- }
- *pp = p->pNext;
- sqlite3_free(p->aRegion);
- sqlite3_free(p);
- }else{
- pp = &p->pNext;
- }
- }
-}
-
-/*
-** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
-** take it now. Return SQLITE_OK if successful, or an SQLite error
-** code otherwise.
-**
-** If the DMS cannot be locked because this is a readonly_shm=1
-** connection and no other process already holds a lock, return
-** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
-*/
-static int winLockSharedMemory(winShmNode *pShmNode){
- int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
-
- if( rc==SQLITE_OK ){
- if( pShmNode->isReadonly ){
- pShmNode->isUnlocked = 1;
- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
- return SQLITE_READONLY_CANTINIT;
- }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
- return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
- "winLockSharedMemory", pShmNode->zFilename);
- }
- }
-
- if( rc==SQLITE_OK ){
- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
- }
-
- return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
-}
-
-/*
-** 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 */
- winShmNode *pShmNode = 0; /* The underlying mmapped file */
- int rc = SQLITE_OK; /* Result code */
- winShmNode *pNew; /* Newly allocated winShmNode */
- int nName; /* Size of zName in bytes */
-
- assert( pDbFd->pShm==0 ); /* Not previously opened */
-
- /* Allocate space for the new sqlite3_shm object. Also speculatively
- ** allocate space for a new winShmNode and filename.
- */
- p = sqlite3MallocZero( sizeof(*p) );
- if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
- nName = sqlite3Strlen30(pDbFd->zPath);
- pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
- if( pNew==0 ){
- sqlite3_free(p);
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- 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{
- int inFlags = SQLITE_OPEN_WAL;
- int outFlags = 0;
-
- pShmNode = pNew;
- pNew = 0;
- ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
- pShmNode->pNext = winShmNodeList;
- winShmNodeList = pShmNode;
-
- if( sqlite3GlobalConfig.bCoreMutex ){
- pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
- if( pShmNode->mutex==0 ){
- rc = SQLITE_IOERR_NOMEM_BKPT;
- goto shm_open_err;
- }
- }
-
- if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
- inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
- }else{
- inFlags |= SQLITE_OPEN_READONLY;
- }
- rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
- (sqlite3_file*)&pShmNode->hFile,
- inFlags, &outFlags);
- if( rc!=SQLITE_OK ){
- rc = winLogError(rc, osGetLastError(), "winOpenShm",
- pShmNode->zFilename);
- goto shm_open_err;
- }
- if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
-
- rc = winLockSharedMemory(pShmNode);
- if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
- }
-
- /* Make the new connection a child of the winShmNode */
- p->pShmNode = pShmNode;
-#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
- 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 rc;
-
- /* Jump here on any error */
-shm_open_err:
- winShmSystemLock(pShmNode, WINSHM_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();
- 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 */
-
- assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
- assert( n>=1 );
- 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) );
- 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;
- assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
- allMask |= pX->sharedMask;
- }
-
- /* Unlock the system-level locks */
- if( (mask & allMask)==0 ){
- rc = winShmSystemLock(pShmNode, WINSHM_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, WINSHM_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, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
- if( rc==SQLITE_OK ){
- assert( (p->sharedMask & mask)==0 );
- p->exclMask |= mask;
- }
- }
- }
- sqlite3_mutex_leave(pShmNode->mutex);
- OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
- osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
- sqlite3ErrName(rc)));
- 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);
- sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
- winShmEnterMutex(); /* Also mutex, for redundancy */
- 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 *pShm = pDbFd->pShm;
- winShmNode *pShmNode;
- DWORD protect = PAGE_READWRITE;
- DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
- int rc = SQLITE_OK;
-
- if( !pShm ){
- rc = winOpenSharedMemory(pDbFd);
- if( rc!=SQLITE_OK ) return rc;
- pShm = pDbFd->pShm;
- }
- pShmNode = pShm->pShmNode;
-
- sqlite3_mutex_enter(pShmNode->mutex);
- if( pShmNode->isUnlocked ){
- rc = winLockSharedMemory(pShmNode);
- if( rc!=SQLITE_OK ) goto shmpage_out;
- pShmNode->isUnlocked = 0;
- }
- 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, osGetLastError(),
- "winShmMap1", pDbFd->zPath);
- goto shmpage_out;
- }
-
- if( szhFile, nByte);
- if( rc!=SQLITE_OK ){
- rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
- "winShmMap2", pDbFd->zPath);
- goto shmpage_out;
- }
- }
-
- /* Map the requested memory region into this processes address space. */
- apNew = (struct ShmRegion *)sqlite3_realloc64(
- pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
- );
- if( !apNew ){
- rc = SQLITE_IOERR_NOMEM_BKPT;
- goto shmpage_out;
- }
- pShmNode->aRegion = apNew;
-
- if( pShmNode->isReadonly ){
- protect = PAGE_READONLY;
- flags = FILE_MAP_READ;
- }
-
- while( pShmNode->nRegion<=iRegion ){
- HANDLE hMap = NULL; /* file-mapping handle */
- void *pMap = 0; /* Mapped memory region */
-
-#if SQLITE_OS_WINRT
- hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
- NULL, protect, nByte, NULL
- );
-#elif defined(SQLITE_WIN32_HAS_WIDE)
- hMap = osCreateFileMappingW(pShmNode->hFile.h,
- NULL, protect, 0, nByte, NULL
- );
-#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
- hMap = osCreateFileMappingA(pShmNode->hFile.h,
- NULL, protect, 0, nByte, NULL
- );
-#endif
- OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
- osGetCurrentProcessId(), pShmNode->nRegion, nByte,
- hMap ? "ok" : "failed"));
- if( hMap ){
- int iOffset = pShmNode->nRegion*szRegion;
- int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
-#if SQLITE_OS_WINRT
- pMap = osMapViewOfFileFromApp(hMap, flags,
- iOffset - iOffsetShift, szRegion + iOffsetShift
- );
-#else
- pMap = osMapViewOfFile(hMap, flags,
- 0, iOffset - iOffsetShift, szRegion + iOffsetShift
- );
-#endif
- OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
- osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
- szRegion, pMap ? "ok" : "failed"));
- }
- if( !pMap ){
- pShmNode->lastErrno = osGetLastError();
- rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
- "winShmMap3", pDbFd->zPath);
- if( hMap ) osCloseHandle(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;
- }
- if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
- sqlite3_mutex_leave(pShmNode->mutex);
- return rc;
-}
-
-#else
-# define winShmMap 0
-# define winShmLock 0
-# define winShmBarrier 0
-# define winShmUnmap 0
-#endif /* #ifndef SQLITE_OMIT_WAL */
-
-/*
-** Cleans up the mapped region of the specified file, if any.
-*/
-#if SQLITE_MAX_MMAP_SIZE>0
-static int winUnmapfile(winFile *pFile){
- assert( pFile!=0 );
- OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
- "mmapSize=%lld, mmapSizeMax=%lld\n",
- osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
- pFile->mmapSize, pFile->mmapSizeMax));
- if( pFile->pMapRegion ){
- if( !osUnmapViewOfFile(pFile->pMapRegion) ){
- pFile->lastErrno = osGetLastError();
- OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
- "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
- pFile->pMapRegion));
- return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
- "winUnmapfile1", pFile->zPath);
- }
- pFile->pMapRegion = 0;
- pFile->mmapSize = 0;
- }
- if( pFile->hMap!=NULL ){
- if( !osCloseHandle(pFile->hMap) ){
- pFile->lastErrno = osGetLastError();
- OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
- osGetCurrentProcessId(), pFile, pFile->hMap));
- return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
- "winUnmapfile2", pFile->zPath);
- }
- pFile->hMap = NULL;
- }
- OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFile));
- return SQLITE_OK;
-}
-
-/*
-** Memory map or remap the file opened by file-descriptor pFd (if the file
-** is already mapped, the existing mapping is replaced by the new). Or, if
-** there already exists a mapping for this file, and there are still
-** outstanding xFetch() references to it, this function is a no-op.
-**
-** If parameter nByte is non-negative, then it is the requested size of
-** the mapping to create. Otherwise, if nByte is less than zero, then the
-** requested size is the size of the file on disk. The actual size of the
-** created mapping is either the requested size or the value configured
-** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
-**
-** SQLITE_OK is returned if no error occurs (even if the mapping is not
-** recreated as a result of outstanding references) or an SQLite error
-** code otherwise.
-*/
-static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
- sqlite3_int64 nMap = nByte;
- int rc;
-
- assert( nMap>=0 || pFd->nFetchOut==0 );
- OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
- osGetCurrentProcessId(), pFd, nByte));
-
- if( pFd->nFetchOut>0 ) return SQLITE_OK;
-
- if( nMap<0 ){
- rc = winFileSize((sqlite3_file*)pFd, &nMap);
- if( rc ){
- OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
- osGetCurrentProcessId(), pFd));
- return SQLITE_IOERR_FSTAT;
- }
- }
- if( nMap>pFd->mmapSizeMax ){
- nMap = pFd->mmapSizeMax;
- }
- nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
-
- if( nMap==0 && pFd->mmapSize>0 ){
- winUnmapfile(pFd);
- }
- if( nMap!=pFd->mmapSize ){
- void *pNew = 0;
- DWORD protect = PAGE_READONLY;
- DWORD flags = FILE_MAP_READ;
-
- winUnmapfile(pFd);
-#ifdef SQLITE_MMAP_READWRITE
- if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
- protect = PAGE_READWRITE;
- flags |= FILE_MAP_WRITE;
- }
-#endif
-#if SQLITE_OS_WINRT
- pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
-#elif defined(SQLITE_WIN32_HAS_WIDE)
- pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
- (DWORD)((nMap>>32) & 0xffffffff),
- (DWORD)(nMap & 0xffffffff), NULL);
-#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
- pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
- (DWORD)((nMap>>32) & 0xffffffff),
- (DWORD)(nMap & 0xffffffff), NULL);
-#endif
- if( pFd->hMap==NULL ){
- pFd->lastErrno = osGetLastError();
- rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
- "winMapfile1", pFd->zPath);
- /* Log the error, but continue normal operation using xRead/xWrite */
- OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
- osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
- return SQLITE_OK;
- }
- assert( (nMap % winSysInfo.dwPageSize)==0 );
- assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
-#if SQLITE_OS_WINRT
- pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
-#else
- pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
-#endif
- if( pNew==NULL ){
- osCloseHandle(pFd->hMap);
- pFd->hMap = NULL;
- pFd->lastErrno = osGetLastError();
- rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
- "winMapfile2", pFd->zPath);
- /* Log the error, but continue normal operation using xRead/xWrite */
- OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
- osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
- return SQLITE_OK;
- }
- pFd->pMapRegion = pNew;
- pFd->mmapSize = nMap;
- }
-
- OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), pFd));
- return SQLITE_OK;
-}
-#endif /* SQLITE_MAX_MMAP_SIZE>0 */
-
-/*
-** If possible, return a pointer to a mapping of file fd starting at offset
-** iOff. The mapping must be valid for at least nAmt bytes.
-**
-** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
-** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
-** Finally, if an error does occur, return an SQLite error code. The final
-** value of *pp is undefined in this case.
-**
-** If this function does return a pointer, the caller must eventually
-** release the reference by calling winUnfetch().
-*/
-static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
-#if SQLITE_MAX_MMAP_SIZE>0
- winFile *pFd = (winFile*)fd; /* The underlying database file */
-#endif
- *pp = 0;
-
- OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
- osGetCurrentProcessId(), fd, iOff, nAmt, pp));
-
-#if SQLITE_MAX_MMAP_SIZE>0
- if( pFd->mmapSizeMax>0 ){
- if( pFd->pMapRegion==0 ){
- int rc = winMapfile(pFd, -1);
- if( rc!=SQLITE_OK ){
- OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
- osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
- return rc;
- }
- }
- if( pFd->mmapSize >= iOff+nAmt ){
- *pp = &((u8 *)pFd->pMapRegion)[iOff];
- pFd->nFetchOut++;
- }
- }
-#endif
-
- OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), fd, pp, *pp));
- return SQLITE_OK;
-}
-
-/*
-** If the third argument is non-NULL, then this function releases a
-** reference obtained by an earlier call to winFetch(). The second
-** argument passed to this function must be the same as the corresponding
-** argument that was passed to the winFetch() invocation.
-**
-** Or, if the third argument is NULL, then this function is being called
-** to inform the VFS layer that, according to POSIX, any existing mapping
-** may now be invalid and should be unmapped.
-*/
-static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
-#if SQLITE_MAX_MMAP_SIZE>0
- winFile *pFd = (winFile*)fd; /* The underlying database file */
-
- /* If p==0 (unmap the entire file) then there must be no outstanding
- ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
- ** then there must be at least one outstanding. */
- assert( (p==0)==(pFd->nFetchOut==0) );
-
- /* If p!=0, it must match the iOff value. */
- assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
-
- OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
- osGetCurrentProcessId(), pFd, iOff, p));
-
- if( p ){
- pFd->nFetchOut--;
- }else{
- /* FIXME: If Windows truly always prevents truncating or deleting a
- ** file while a mapping is held, then the following winUnmapfile() call
- ** is unnecessary can be omitted - potentially improving
- ** performance. */
- winUnmapfile(pFd);
- }
-
- assert( pFd->nFetchOut>=0 );
-#endif
-
- OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
- osGetCurrentProcessId(), fd));
- return SQLITE_OK;
-}
-
-/*
-** 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 const sqlite3_io_methods winIoMethod = {
- 3, /* iVersion */
- winClose, /* xClose */
- winRead, /* xRead */
- winWrite, /* xWrite */
- winTruncate, /* xTruncate */
- winSync, /* xSync */
- winFileSize, /* xFileSize */
- winLock, /* xLock */
- winUnlock, /* xUnlock */
- winCheckReservedLock, /* xCheckReservedLock */
- winFileControl, /* xFileControl */
- winSectorSize, /* xSectorSize */
- winDeviceCharacteristics, /* xDeviceCharacteristics */
- winShmMap, /* xShmMap */
- winShmLock, /* xShmLock */
- winShmBarrier, /* xShmBarrier */
- winShmUnmap, /* xShmUnmap */
- winFetch, /* xFetch */
- winUnfetch /* xUnfetch */
-};
-
-/*
-** This vector defines all the methods that can operate on an
-** sqlite3_file for win32 without performing any locking.
-*/
-static const sqlite3_io_methods winIoNolockMethod = {
- 3, /* iVersion */
- winClose, /* xClose */
- winRead, /* xRead */
- winWrite, /* xWrite */
- winTruncate, /* xTruncate */
- winSync, /* xSync */
- winFileSize, /* xFileSize */
- winNolockLock, /* xLock */
- winNolockUnlock, /* xUnlock */
- winNolockCheckReservedLock, /* xCheckReservedLock */
- winFileControl, /* xFileControl */
- winSectorSize, /* xSectorSize */
- winDeviceCharacteristics, /* xDeviceCharacteristics */
- winShmMap, /* xShmMap */
- winShmLock, /* xShmLock */
- winShmBarrier, /* xShmBarrier */
- winShmUnmap, /* xShmUnmap */
- winFetch, /* xFetch */
- winUnfetch /* xUnfetch */
-};
-
-static winVfsAppData winAppData = {
- &winIoMethod, /* pMethod */
- 0, /* pAppData */
- 0 /* bNoLock */
-};
-
-static winVfsAppData winNolockAppData = {
- &winIoNolockMethod, /* pMethod */
- 0, /* pAppData */
- 1 /* bNoLock */
-};
-
-/****************************************************************************
-**************************** sqlite3_vfs methods ****************************
-**
-** This division contains the implementation of methods on the
-** sqlite3_vfs object.
-*/
-
-#if defined(__CYGWIN__)
-/*
-** Convert a filename from whatever the underlying operating system
-** supports for filenames into UTF-8. Space to hold the result is
-** obtained from malloc and must be freed by the calling function.
-*/
-static char *winConvertToUtf8Filename(const void *zFilename){
- char *zConverted = 0;
- if( osIsNT() ){
- zConverted = winUnicodeToUtf8(zFilename);
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
- }
-#endif
- /* caller will handle out of memory */
- return zConverted;
-}
-#endif
-
-/*
-** 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 void *winConvertFromUtf8Filename(const char *zFilename){
- void *zConverted = 0;
- if( osIsNT() ){
- zConverted = winUtf8ToUnicode(zFilename);
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
- }
-#endif
- /* caller will handle out of memory */
- return zConverted;
-}
-
-/*
-** This function returns non-zero if the specified UTF-8 string buffer
-** ends with a directory separator character or one was successfully
-** added to it.
-*/
-static int winMakeEndInDirSep(int nBuf, char *zBuf){
- if( zBuf ){
- int nLen = sqlite3Strlen30(zBuf);
- if( nLen>0 ){
- if( winIsDirSep(zBuf[nLen-1]) ){
- return 1;
- }else if( nLen+1mxPathname; nBuf = nMax + 2;
- zBuf = sqlite3MallocZero( nBuf );
- if( !zBuf ){
- OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
- return SQLITE_IOERR_NOMEM_BKPT;
- }
-
- /* Figure out the effective temporary directory. First, check if one
- ** has been explicitly set by the application; otherwise, use the one
- ** configured by the operating system.
- */
- nDir = nMax - (nPre + 15);
- assert( nDir>0 );
- if( sqlite3_temp_directory ){
- int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
- if( nDirLen>0 ){
- if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
- nDirLen++;
- }
- if( nDirLen>nDir ){
- sqlite3_free(zBuf);
- OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
- return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
- }
- sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
- }
- }
-#if defined(__CYGWIN__)
- else{
- static const char *azDirs[] = {
- 0, /* getenv("SQLITE_TMPDIR") */
- 0, /* getenv("TMPDIR") */
- 0, /* getenv("TMP") */
- 0, /* getenv("TEMP") */
- 0, /* getenv("USERPROFILE") */
- "/var/tmp",
- "/usr/tmp",
- "/tmp",
- ".",
- 0 /* List terminator */
- };
- unsigned int i;
- const char *zDir = 0;
-
- if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
- if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
- if( !azDirs[2] ) azDirs[2] = getenv("TMP");
- if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
- if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
- for(i=0; i/etilqs_XXXXXXXXXXXXXXX\0\0"
- **
- ** If not, return SQLITE_ERROR. The number 17 is used here in order to
- ** account for the space used by the 15 character random suffix and the
- ** two trailing NUL characters. The final directory separator character
- ** has already added if it was not already present.
- */
- nLen = sqlite3Strlen30(zBuf);
- if( (nLen + nPre + 17) > nBuf ){
- sqlite3_free(zBuf);
- OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
- return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
- }
-
- sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
-
- 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;
- zBuf[j+1] = 0;
- *pzBuf = zBuf;
-
- OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
- return SQLITE_OK;
-}
-
-/*
-** Return TRUE if the named file is really a directory. Return false if
-** it is something other than a directory, or if there is any kind of memory
-** allocation failure.
-*/
-static int winIsDir(const void *zConverted){
- DWORD attr;
- int rc = 0;
- DWORD lastErrno;
-
- if( osIsNT() ){
- int cnt = 0;
- WIN32_FILE_ATTRIBUTE_DATA sAttrData;
- memset(&sAttrData, 0, sizeof(sAttrData));
- while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
- GetFileExInfoStandard,
- &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
- if( !rc ){
- return 0; /* Invalid name? */
- }
- attr = sAttrData.dwFileAttributes;
-#if SQLITE_OS_WINCE==0
- }else{
- attr = osGetFileAttributesA((char*)zConverted);
-#endif
- }
- return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
-}
-
-/* forward reference */
-static int winAccess(
- sqlite3_vfs *pVfs, /* Not used on win32 */
- const char *zFilename, /* Name of file to check */
- int flags, /* Type of test to make on this file */
- int *pResOut /* OUT: Result */
-);
-
-/*
-** Open a file.
-*/
-static int winOpen(
- sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
- const char *zName, /* Name of the file (UTF-8) */
- sqlite3_file *id, /* Write the SQLite file handle here */
- int flags, /* Open mode flags */
- int *pOutFlags /* Status return flags */
-){
- HANDLE h;
- DWORD lastErrno = 0;
- DWORD dwDesiredAccess;
- DWORD dwShareMode;
- DWORD dwCreationDisposition;
- DWORD dwFlagsAndAttributes = 0;
-#if SQLITE_OS_WINCE
- int isTemp = 0;
-#endif
- winVfsAppData *pAppData;
- winFile *pFile = (winFile*)id;
- void *zConverted; /* Filename in OS encoding */
- const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
- int cnt = 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.
- */
- char *zTmpname = 0; /* For temporary filename, if necessary. */
-
- int rc = SQLITE_OK; /* Function Return Code */
-#if !defined(NDEBUG) || SQLITE_OS_WINCE
- int eType = flags&0xFFFFFF00; /* Type of file to open */
-#endif
-
- int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
- int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
- int isCreate = (flags & SQLITE_OPEN_CREATE);
- int isReadonly = (flags & SQLITE_OPEN_READONLY);
- int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
-
-#ifndef NDEBUG
- int isOpenJournal = (isCreate && (
- eType==SQLITE_OPEN_MASTER_JOURNAL
- || eType==SQLITE_OPEN_MAIN_JOURNAL
- || eType==SQLITE_OPEN_WAL
- ));
-#endif
-
- OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
- zUtf8Name, id, flags, pOutFlags));
-
- /* 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.
- */
- assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
- assert(isCreate==0 || isReadWrite);
- assert(isExclusive==0 || isCreate);
- assert(isDelete==0 || isCreate);
-
- /* The main DB, main journal, WAL file and master journal are never
- ** automatically deleted. Nor are they ever temporary files. */
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
- assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
-
- /* Assert that the upper layer has set one of the "file-type" flags. */
- 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
- );
-
- assert( pFile!=0 );
- memset(pFile, 0, sizeof(winFile));
- pFile->h = INVALID_HANDLE_VALUE;
-
-#if SQLITE_OS_WINRT
- if( !zUtf8Name && !sqlite3_temp_directory ){
- sqlite3_log(SQLITE_ERROR,
- "sqlite3_temp_directory variable should be set for WinRT");
- }
-#endif
-
- /* If the second argument to this function is NULL, generate a
- ** temporary file name to use
- */
- if( !zUtf8Name ){
- assert( isDelete && !isOpenJournal );
- rc = winGetTempname(pVfs, &zTmpname);
- if( rc!=SQLITE_OK ){
- OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
- return rc;
- }
- zUtf8Name = zTmpname;
- }
-
- /* Database filenames are double-zero terminated if they are not
- ** URIs with parameters. Hence, they can always be passed into
- ** sqlite3_uri_parameter().
- */
- assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
- zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
-
- /* Convert the filename to the system encoding. */
- zConverted = winConvertFromUtf8Filename(zUtf8Name);
- if( zConverted==0 ){
- sqlite3_free(zTmpname);
- OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
- return SQLITE_IOERR_NOMEM_BKPT;
- }
-
- if( winIsDir(zConverted) ){
- sqlite3_free(zConverted);
- sqlite3_free(zTmpname);
- OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
- return SQLITE_CANTOPEN_ISDIR;
- }
-
- if( isReadWrite ){
- dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
- }else{
- dwDesiredAccess = 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 = CREATE_NEW;
- }else if( isCreate ){
- /* Open existing file, or create if it doesn't exist */
- dwCreationDisposition = OPEN_ALWAYS;
- }else{
- /* Opens a file, only if it exists. */
- dwCreationDisposition = OPEN_EXISTING;
- }
-
- dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
-
- if( isDelete ){
-#if SQLITE_OS_WINCE
- dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
- isTemp = 1;
-#else
- dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
- | FILE_ATTRIBUTE_HIDDEN
- | FILE_FLAG_DELETE_ON_CLOSE;
-#endif
- }else{
- dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
- }
- /* Reports from the internet are that performance is always
- ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
-#if SQLITE_OS_WINCE
- dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
-#endif
-
- if( osIsNT() ){
-#if SQLITE_OS_WINRT
- CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
- extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
- extendedParameters.dwFileAttributes =
- dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
- extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
- extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
- extendedParameters.lpSecurityAttributes = NULL;
- extendedParameters.hTemplateFile = NULL;
- do{
- h = osCreateFile2((LPCWSTR)zConverted,
- dwDesiredAccess,
- dwShareMode,
- dwCreationDisposition,
- &extendedParameters);
- if( h!=INVALID_HANDLE_VALUE ) break;
- if( isReadWrite ){
- int rc2, isRO = 0;
- sqlite3BeginBenignMalloc();
- rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
- sqlite3EndBenignMalloc();
- if( rc2==SQLITE_OK && isRO ) break;
- }
- }while( winRetryIoerr(&cnt, &lastErrno) );
-#else
- do{
- h = osCreateFileW((LPCWSTR)zConverted,
- dwDesiredAccess,
- dwShareMode, NULL,
- dwCreationDisposition,
- dwFlagsAndAttributes,
- NULL);
- if( h!=INVALID_HANDLE_VALUE ) break;
- if( isReadWrite ){
- int rc2, isRO = 0;
- sqlite3BeginBenignMalloc();
- rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
- sqlite3EndBenignMalloc();
- if( rc2==SQLITE_OK && isRO ) break;
- }
- }while( winRetryIoerr(&cnt, &lastErrno) );
-#endif
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- do{
- h = osCreateFileA((LPCSTR)zConverted,
- dwDesiredAccess,
- dwShareMode, NULL,
- dwCreationDisposition,
- dwFlagsAndAttributes,
- NULL);
- if( h!=INVALID_HANDLE_VALUE ) break;
- if( isReadWrite ){
- int rc2, isRO = 0;
- sqlite3BeginBenignMalloc();
- rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
- sqlite3EndBenignMalloc();
- if( rc2==SQLITE_OK && isRO ) break;
- }
- }while( winRetryIoerr(&cnt, &lastErrno) );
- }
-#endif
- winLogIoerr(cnt, __LINE__);
-
- OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
- dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
-
- if( h==INVALID_HANDLE_VALUE ){
- sqlite3_free(zConverted);
- sqlite3_free(zTmpname);
- if( isReadWrite && !isExclusive ){
- return winOpen(pVfs, zName, id,
- ((flags|SQLITE_OPEN_READONLY) &
- ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
- pOutFlags);
- }else{
- pFile->lastErrno = lastErrno;
- winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
- return SQLITE_CANTOPEN_BKPT;
- }
- }
-
- if( pOutFlags ){
- if( isReadWrite ){
- *pOutFlags = SQLITE_OPEN_READWRITE;
- }else{
- *pOutFlags = SQLITE_OPEN_READONLY;
- }
- }
-
- OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
- "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
- *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
-
- pAppData = (winVfsAppData*)pVfs->pAppData;
-
-#if SQLITE_OS_WINCE
- {
- if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
- && ((pAppData==NULL) || !pAppData->bNoLock)
- && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
- ){
- osCloseHandle(h);
- sqlite3_free(zConverted);
- sqlite3_free(zTmpname);
- OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
- return rc;
- }
- }
- if( isTemp ){
- pFile->zDeleteOnClose = zConverted;
- }else
-#endif
- {
- sqlite3_free(zConverted);
- }
-
- sqlite3_free(zTmpname);
- pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
- pFile->pVfs = pVfs;
- pFile->h = h;
- if( isReadonly ){
- pFile->ctrlFlags |= WINFILE_RDONLY;
- }
- if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
- pFile->ctrlFlags |= WINFILE_PSOW;
- }
- pFile->lastErrno = NO_ERROR;
- pFile->zPath = zName;
-#if SQLITE_MAX_MMAP_SIZE>0
- pFile->hMap = NULL;
- pFile->pMapRegion = 0;
- pFile->mmapSize = 0;
- pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
-#endif
-
- OpenCounter(+1);
- 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 winDelete(
- sqlite3_vfs *pVfs, /* Not used on win32 */
- const char *zFilename, /* Name of file to delete */
- int syncDir /* Not used on win32 */
-){
- int cnt = 0;
- int rc;
- DWORD attr;
- DWORD lastErrno = 0;
- void *zConverted;
- UNUSED_PARAMETER(pVfs);
- UNUSED_PARAMETER(syncDir);
-
- SimulateIOError(return SQLITE_IOERR_DELETE);
- OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
-
- zConverted = winConvertFromUtf8Filename(zFilename);
- if( zConverted==0 ){
- OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- if( osIsNT() ){
- do {
-#if SQLITE_OS_WINRT
- WIN32_FILE_ATTRIBUTE_DATA sAttrData;
- memset(&sAttrData, 0, sizeof(sAttrData));
- if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
- &sAttrData) ){
- attr = sAttrData.dwFileAttributes;
- }else{
- lastErrno = osGetLastError();
- if( lastErrno==ERROR_FILE_NOT_FOUND
- || lastErrno==ERROR_PATH_NOT_FOUND ){
- rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
- }else{
- rc = SQLITE_ERROR;
- }
- break;
- }
-#else
- attr = osGetFileAttributesW(zConverted);
-#endif
- if ( attr==INVALID_FILE_ATTRIBUTES ){
- lastErrno = osGetLastError();
- if( lastErrno==ERROR_FILE_NOT_FOUND
- || lastErrno==ERROR_PATH_NOT_FOUND ){
- rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
- }else{
- rc = SQLITE_ERROR;
- }
- break;
- }
- if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
- rc = SQLITE_ERROR; /* Files only. */
- break;
- }
- if ( osDeleteFileW(zConverted) ){
- rc = SQLITE_OK; /* Deleted OK. */
- break;
- }
- if ( !winRetryIoerr(&cnt, &lastErrno) ){
- rc = SQLITE_ERROR; /* No more retries. */
- break;
- }
- } while(1);
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- do {
- attr = osGetFileAttributesA(zConverted);
- if ( attr==INVALID_FILE_ATTRIBUTES ){
- lastErrno = osGetLastError();
- if( lastErrno==ERROR_FILE_NOT_FOUND
- || lastErrno==ERROR_PATH_NOT_FOUND ){
- rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
- }else{
- rc = SQLITE_ERROR;
- }
- break;
- }
- if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
- rc = SQLITE_ERROR; /* Files only. */
- break;
- }
- if ( osDeleteFileA(zConverted) ){
- rc = SQLITE_OK; /* Deleted OK. */
- break;
- }
- if ( !winRetryIoerr(&cnt, &lastErrno) ){
- rc = SQLITE_ERROR; /* No more retries. */
- break;
- }
- } while(1);
- }
-#endif
- if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
- rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
- }else{
- winLogIoerr(cnt, __LINE__);
- }
- sqlite3_free(zConverted);
- OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
- return rc;
-}
-
-/*
-** Check the existence and status of a file.
-*/
-static int winAccess(
- sqlite3_vfs *pVfs, /* Not used on win32 */
- const char *zFilename, /* Name of file to check */
- int flags, /* Type of test to make on this file */
- int *pResOut /* OUT: Result */
-){
- DWORD attr;
- int rc = 0;
- DWORD lastErrno = 0;
- void *zConverted;
- UNUSED_PARAMETER(pVfs);
-
- SimulateIOError( return SQLITE_IOERR_ACCESS; );
- OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
- zFilename, flags, pResOut));
-
- zConverted = winConvertFromUtf8Filename(zFilename);
- if( zConverted==0 ){
- OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- if( osIsNT() ){
- int cnt = 0;
- WIN32_FILE_ATTRIBUTE_DATA sAttrData;
- memset(&sAttrData, 0, sizeof(sAttrData));
- while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
- GetFileExInfoStandard,
- &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
- if( rc ){
- /* 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{
- winLogIoerr(cnt, __LINE__);
- if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
- sqlite3_free(zConverted);
- return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
- zFilename);
- }else{
- attr = INVALID_FILE_ATTRIBUTES;
- }
- }
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- attr = osGetFileAttributesA((char*)zConverted);
- }
-#endif
- sqlite3_free(zConverted);
- switch( flags ){
- case SQLITE_ACCESS_READ:
- case SQLITE_ACCESS_EXISTS:
- rc = attr!=INVALID_FILE_ATTRIBUTES;
- break;
- case SQLITE_ACCESS_READWRITE:
- rc = attr!=INVALID_FILE_ATTRIBUTES &&
- (attr & FILE_ATTRIBUTE_READONLY)==0;
- break;
- default:
- assert(!"Invalid flags argument");
- }
- *pResOut = rc;
- OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
- zFilename, pResOut, *pResOut));
- return SQLITE_OK;
-}
-
-/*
-** Returns non-zero if the specified path name starts with a drive letter
-** followed by a colon character.
-*/
-static BOOL winIsDriveLetterAndColon(
- const char *zPathname
-){
- return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
-}
-
-/*
-** Returns non-zero if the specified path name should be used verbatim. If
-** non-zero is returned from this function, the calling function must simply
-** use the provided path name verbatim -OR- resolve it into a full path name
-** using the GetFullPathName Win32 API function (if available).
-*/
-static BOOL winIsVerbatimPathname(
- const char *zPathname
-){
- /*
- ** If the path name starts with a forward slash or a backslash, it is either
- ** a legal UNC name, a volume relative path, or an absolute path name in the
- ** "Unix" format on Windows. There is no easy way to differentiate between
- ** the final two cases; therefore, we return the safer return value of TRUE
- ** so that callers of this function will simply use it verbatim.
- */
- if ( winIsDirSep(zPathname[0]) ){
- return TRUE;
- }
-
- /*
- ** If the path name starts with a letter and a colon it is either a volume
- ** relative path or an absolute path. Callers of this function must not
- ** attempt to treat it as a relative path name (i.e. they should simply use
- ** it verbatim).
- */
- if ( winIsDriveLetterAndColon(zPathname) ){
- return TRUE;
- }
-
- /*
- ** If we get to this point, the path name should almost certainly be a purely
- ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
- */
- return FALSE;
-}
-
-/*
-** 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 */
- const char *zRelative, /* Possibly relative input path */
- int nFull, /* Size of output buffer in bytes */
- char *zFull /* Output buffer */
-){
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
- DWORD nByte;
- void *zConverted;
- char *zOut;
-#endif
-
- /* If this path name begins with "/X:", where "X" is any alphabetic
- ** character, discard the initial "/" from the pathname.
- */
- if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
- zRelative++;
- }
-
-#if defined(__CYGWIN__)
- SimulateIOError( return SQLITE_ERROR );
- UNUSED_PARAMETER(nFull);
- assert( nFull>=pVfs->mxPathname );
- if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
- /*
- ** NOTE: We are dealing with a relative path name and the data
- ** directory has been set. Therefore, use it as the basis
- ** for converting the relative path name to an absolute
- ** one by prepending the data directory and a slash.
- */
- char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
- if( !zOut ){
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- if( cygwin_conv_path(
- (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
- CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
- sqlite3_free(zOut);
- return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
- "winFullPathname1", zRelative);
- }else{
- char *zUtf8 = winConvertToUtf8Filename(zOut);
- if( !zUtf8 ){
- sqlite3_free(zOut);
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
- sqlite3_data_directory, winGetDirSep(), zUtf8);
- sqlite3_free(zUtf8);
- sqlite3_free(zOut);
- }
- }else{
- char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
- if( !zOut ){
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- if( cygwin_conv_path(
- (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
- zRelative, zOut, pVfs->mxPathname+1)<0 ){
- sqlite3_free(zOut);
- return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
- "winFullPathname2", zRelative);
- }else{
- char *zUtf8 = winConvertToUtf8Filename(zOut);
- if( !zUtf8 ){
- sqlite3_free(zOut);
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
- sqlite3_free(zUtf8);
- sqlite3_free(zOut);
- }
- }
- return SQLITE_OK;
-#endif
-
-#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
- SimulateIOError( return SQLITE_ERROR );
- /* WinCE has no concept of a relative pathname, or so I am told. */
- /* WinRT has no way to convert a relative path to an absolute one. */
- if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
- /*
- ** NOTE: We are dealing with a relative path name and the data
- ** directory has been set. Therefore, use it as the basis
- ** for converting the relative path name to an absolute
- ** one by prepending the data directory and a backslash.
- */
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
- sqlite3_data_directory, winGetDirSep(), zRelative);
- }else{
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
- }
- return SQLITE_OK;
-#endif
-
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
- /* 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.
- */
- SimulateIOError( return SQLITE_ERROR );
- if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
- /*
- ** NOTE: We are dealing with a relative path name and the data
- ** directory has been set. Therefore, use it as the basis
- ** for converting the relative path name to an absolute
- ** one by prepending the data directory and a backslash.
- */
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
- sqlite3_data_directory, winGetDirSep(), zRelative);
- return SQLITE_OK;
- }
- zConverted = winConvertFromUtf8Filename(zRelative);
- if( zConverted==0 ){
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- if( osIsNT() ){
- LPWSTR zTemp;
- nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
- if( nByte==0 ){
- sqlite3_free(zConverted);
- return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
- "winFullPathname1", zRelative);
- }
- nByte += 3;
- zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
- if( zTemp==0 ){
- sqlite3_free(zConverted);
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
- if( nByte==0 ){
- sqlite3_free(zConverted);
- sqlite3_free(zTemp);
- return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
- "winFullPathname2", zRelative);
- }
- sqlite3_free(zConverted);
- zOut = winUnicodeToUtf8(zTemp);
- sqlite3_free(zTemp);
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- char *zTemp;
- nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
- if( nByte==0 ){
- sqlite3_free(zConverted);
- return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
- "winFullPathname3", zRelative);
- }
- nByte += 3;
- zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
- if( zTemp==0 ){
- sqlite3_free(zConverted);
- return SQLITE_IOERR_NOMEM_BKPT;
- }
- nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
- if( nByte==0 ){
- sqlite3_free(zConverted);
- sqlite3_free(zTemp);
- return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
- "winFullPathname4", zRelative);
- }
- sqlite3_free(zConverted);
- zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
- sqlite3_free(zTemp);
- }
-#endif
- if( zOut ){
- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
- sqlite3_free(zOut);
- return SQLITE_OK;
- }else{
- return SQLITE_IOERR_NOMEM_BKPT;
- }
-#endif
-}
-
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-/*
-** Interfaces for opening a shared library, finding entry points
-** within the shared library, and closing the shared library.
-*/
-static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
- HANDLE h;
-#if defined(__CYGWIN__)
- int nFull = pVfs->mxPathname+1;
- char *zFull = sqlite3MallocZero( nFull );
- void *zConverted = 0;
- if( zFull==0 ){
- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
- return 0;
- }
- if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
- sqlite3_free(zFull);
- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
- return 0;
- }
- zConverted = winConvertFromUtf8Filename(zFull);
- sqlite3_free(zFull);
-#else
- void *zConverted = winConvertFromUtf8Filename(zFilename);
- UNUSED_PARAMETER(pVfs);
-#endif
- if( zConverted==0 ){
- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
- return 0;
- }
- if( osIsNT() ){
-#if SQLITE_OS_WINRT
- h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
-#else
- h = osLoadLibraryW((LPCWSTR)zConverted);
-#endif
- }
-#ifdef SQLITE_WIN32_HAS_ANSI
- else{
- h = osLoadLibraryA((char*)zConverted);
- }
-#endif
- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
- sqlite3_free(zConverted);
- return (void*)h;
-}
-static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
- UNUSED_PARAMETER(pVfs);
- winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
-}
-static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
- FARPROC proc;
- UNUSED_PARAMETER(pVfs);
- proc = osGetProcAddressA((HANDLE)pH, zSym);
- OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
- (void*)pH, zSym, (void*)proc));
- return (void(*)(void))proc;
-}
-static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
- UNUSED_PARAMETER(pVfs);
- osFreeLibrary((HANDLE)pHandle);
- OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
-}
-#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
- #define winDlOpen 0
- #define winDlError 0
- #define winDlSym 0
- #define winDlClose 0
-#endif
-
-/* State information for the randomness gatherer. */
-typedef struct EntropyGatherer EntropyGatherer;
-struct EntropyGatherer {
- unsigned char *a; /* Gather entropy into this buffer */
- int na; /* Size of a[] in bytes */
- int i; /* XOR next input into a[i] */
- int nXor; /* Number of XOR operations done */
-};
-
-#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
-/* Mix sz bytes of entropy into p. */
-static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
- int j, k;
- for(j=0, k=p->i; ja[k++] ^= x[j];
- if( k>=p->na ) k = 0;
- }
- p->i = k;
- p->nXor += sz;
-}
-#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
-
-/*
-** Write up to nBuf bytes of randomness into zBuf.
-*/
-static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
-#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
- UNUSED_PARAMETER(pVfs);
- memset(zBuf, 0, nBuf);
- return nBuf;
-#else
- EntropyGatherer e;
- UNUSED_PARAMETER(pVfs);
- memset(zBuf, 0, nBuf);
- e.a = (unsigned char*)zBuf;
- e.na = nBuf;
- e.nXor = 0;
- e.i = 0;
- {
- SYSTEMTIME x;
- osGetSystemTime(&x);
- xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
- }
- {
- DWORD pid = osGetCurrentProcessId();
- xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
- }
-#if SQLITE_OS_WINRT
- {
- ULONGLONG cnt = osGetTickCount64();
- xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
- }
-#else
- {
- DWORD cnt = osGetTickCount();
- xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
- }
-#endif /* SQLITE_OS_WINRT */
- {
- LARGE_INTEGER i;
- osQueryPerformanceCounter(&i);
- xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
- }
-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
- {
- UUID id;
- memset(&id, 0, sizeof(UUID));
- osUuidCreate(&id);
- xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
- memset(&id, 0, sizeof(UUID));
- osUuidCreateSequential(&id);
- xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
- }
-#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
- return e.nXor>nBuf ? nBuf : e.nXor;
-#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
-}
-
-
-/*
-** Sleep for a little while. Return the amount of time slept.
-*/
-static int winSleep(sqlite3_vfs *pVfs, int microsec){
- sqlite3_win32_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.
-*/
-#ifdef SQLITE_TEST
-SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
-#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 SQLITE_OK. Return SQLITE_ERROR if the time and date
-** cannot be found.
-*/
-static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
- /* FILETIME structure is a 64-bit value representing the number of
- 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
- */
- FILETIME ft;
- static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
-#ifdef SQLITE_TEST
- static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
-#endif
- /* 2^32 - to avoid use of LL and warnings in gcc */
- static const sqlite3_int64 max32BitValue =
- (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
- (sqlite3_int64)294967296;
-
-#if SQLITE_OS_WINCE
- SYSTEMTIME time;
- osGetSystemTime(&time);
- /* if SystemTimeToFileTime() fails, it returns zero. */
- if (!osSystemTimeToFileTime(&time,&ft)){
- return SQLITE_ERROR;
- }
-#else
- osGetSystemTimeAsFileTime( &ft );
-#endif
-
- *piNow = winFiletimeEpoch +
- ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
- (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
-
-#ifdef SQLITE_TEST
- if( sqlite3_current_time ){
- *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
- }
-#endif
- UNUSED_PARAMETER(pVfs);
- return SQLITE_OK;
-}
-
-/*
-** 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, double *prNow){
- int rc;
- sqlite3_int64 i;
- rc = winCurrentTimeInt64(pVfs, &i);
- if( !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, char *zBuf){
-** 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, char *zBuf){
- DWORD e = osGetLastError();
- UNUSED_PARAMETER(pVfs);
- if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
- return e;
-}
-
-/*
-** Initialize and deinitialize the operating system interface.
-*/
-SQLITE_API int sqlite3_os_init(void){
- static sqlite3_vfs winVfs = {
- 3, /* iVersion */
- sizeof(winFile), /* szOsFile */
- SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
- 0, /* pNext */
- "win32", /* zName */
- &winAppData, /* pAppData */
- winOpen, /* xOpen */
- winDelete, /* xDelete */
- winAccess, /* xAccess */
- winFullPathname, /* xFullPathname */
- winDlOpen, /* xDlOpen */
- winDlError, /* xDlError */
- winDlSym, /* xDlSym */
- winDlClose, /* xDlClose */
- winRandomness, /* xRandomness */
- winSleep, /* xSleep */
- winCurrentTime, /* xCurrentTime */
- winGetLastError, /* xGetLastError */
- winCurrentTimeInt64, /* xCurrentTimeInt64 */
- winSetSystemCall, /* xSetSystemCall */
- winGetSystemCall, /* xGetSystemCall */
- winNextSystemCall, /* xNextSystemCall */
- };
-#if defined(SQLITE_WIN32_HAS_WIDE)
- static sqlite3_vfs winLongPathVfs = {
- 3, /* iVersion */
- sizeof(winFile), /* szOsFile */
- SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
- 0, /* pNext */
- "win32-longpath", /* zName */
- &winAppData, /* pAppData */
- winOpen, /* xOpen */
- winDelete, /* xDelete */
- winAccess, /* xAccess */
- winFullPathname, /* xFullPathname */
- winDlOpen, /* xDlOpen */
- winDlError, /* xDlError */
- winDlSym, /* xDlSym */
- winDlClose, /* xDlClose */
- winRandomness, /* xRandomness */
- winSleep, /* xSleep */
- winCurrentTime, /* xCurrentTime */
- winGetLastError, /* xGetLastError */
- winCurrentTimeInt64, /* xCurrentTimeInt64 */
- winSetSystemCall, /* xSetSystemCall */
- winGetSystemCall, /* xGetSystemCall */
- winNextSystemCall, /* xNextSystemCall */
- };
-#endif
- static sqlite3_vfs winNolockVfs = {
- 3, /* iVersion */
- sizeof(winFile), /* szOsFile */
- SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
- 0, /* pNext */
- "win32-none", /* zName */
- &winNolockAppData, /* pAppData */
- winOpen, /* xOpen */
- winDelete, /* xDelete */
- winAccess, /* xAccess */
- winFullPathname, /* xFullPathname */
- winDlOpen, /* xDlOpen */
- winDlError, /* xDlError */
- winDlSym, /* xDlSym */
- winDlClose, /* xDlClose */
- winRandomness, /* xRandomness */
- winSleep, /* xSleep */
- winCurrentTime, /* xCurrentTime */
- winGetLastError, /* xGetLastError */
- winCurrentTimeInt64, /* xCurrentTimeInt64 */
- winSetSystemCall, /* xSetSystemCall */
- winGetSystemCall, /* xGetSystemCall */
- winNextSystemCall, /* xNextSystemCall */
- };
-#if defined(SQLITE_WIN32_HAS_WIDE)
- static sqlite3_vfs winLongPathNolockVfs = {
- 3, /* iVersion */
- sizeof(winFile), /* szOsFile */
- SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
- 0, /* pNext */
- "win32-longpath-none", /* zName */
- &winNolockAppData, /* pAppData */
- winOpen, /* xOpen */
- winDelete, /* xDelete */
- winAccess, /* xAccess */
- winFullPathname, /* xFullPathname */
- winDlOpen, /* xDlOpen */
- winDlError, /* xDlError */
- winDlSym, /* xDlSym */
- winDlClose, /* xDlClose */
- winRandomness, /* xRandomness */
- winSleep, /* xSleep */
- winCurrentTime, /* xCurrentTime */
- winGetLastError, /* xGetLastError */
- winCurrentTimeInt64, /* xCurrentTimeInt64 */
- winSetSystemCall, /* xSetSystemCall */
- winGetSystemCall, /* xGetSystemCall */
- winNextSystemCall, /* xNextSystemCall */
- };
-#endif
-
- /* Double-check that the aSyscall[] array has been constructed
- ** correctly. See ticket [bb3a86e890c8e96ab] */
- assert( ArraySize(aSyscall)==80 );
-
- /* get memory map allocation granularity */
- memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
-#if SQLITE_OS_WINRT
- osGetNativeSystemInfo(&winSysInfo);
-#else
- osGetSystemInfo(&winSysInfo);
-#endif
- assert( winSysInfo.dwAllocationGranularity>0 );
- assert( winSysInfo.dwPageSize>0 );
-
- sqlite3_vfs_register(&winVfs, 1);
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- sqlite3_vfs_register(&winLongPathVfs, 0);
-#endif
-
- sqlite3_vfs_register(&winNolockVfs, 0);
-
-#if defined(SQLITE_WIN32_HAS_WIDE)
- sqlite3_vfs_register(&winLongPathNolockVfs, 0);
-#endif
-
-#ifndef SQLITE_OMIT_WAL
- winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
-#endif
-
- return SQLITE_OK;
-}
-
-SQLITE_API int sqlite3_os_end(void){
-#if SQLITE_OS_WINRT
- if( sleepObj!=NULL ){
- osCloseHandle(sleepObj);
- sleepObj = NULL;
- }
-#endif
-
-#ifndef SQLITE_OMIT_WAL
- winBigLock = 0;
-#endif
-
- return SQLITE_OK;
-}
-
-#endif /* SQLITE_OS_WIN */
-
-/************** End of os_win.c **********************************************/
-/************** Begin file memdb.c *******************************************/
-/*
-** 2016-09-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 implements an in-memory VFS. A database is held as a contiguous
-** block of memory.
-**
-** This file also implements interface sqlite3_serialize() and
-** sqlite3_deserialize().
-*/
-/* #include "sqliteInt.h" */
-#ifdef SQLITE_ENABLE_DESERIALIZE
-
-/*
-** Forward declaration of objects used by this utility
-*/
-typedef struct sqlite3_vfs MemVfs;
-typedef struct MemFile MemFile;
-
-/* Access to a lower-level VFS that (might) implement dynamic loading,
-** access to randomness, etc.
-*/
-#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
-
-/* An open file */
-struct MemFile {
- sqlite3_file base; /* IO methods */
- sqlite3_int64 sz; /* Size of the file */
- sqlite3_int64 szAlloc; /* Space allocated to aData */
- sqlite3_int64 szMax; /* Maximum allowed size of the file */
- unsigned char *aData; /* content of the file */
- int nMmap; /* Number of memory mapped pages */
- unsigned mFlags; /* Flags */
- int eLock; /* Most recent lock against this file */
-};
-
-/*
-** Methods for MemFile
-*/
-static int memdbClose(sqlite3_file*);
-static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
-static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
-static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
-static int memdbSync(sqlite3_file*, int flags);
-static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
-static int memdbLock(sqlite3_file*, int);
-/* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
-static int memdbFileControl(sqlite3_file*, int op, void *pArg);
-/* static int memdbSectorSize(sqlite3_file*); // not used */
-static int memdbDeviceCharacteristics(sqlite3_file*);
-static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
-static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
-
-/*
-** Methods for MemVfs
-*/
-static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
-/* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
-static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
-static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
-static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
-static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
-static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
-static void memdbDlClose(sqlite3_vfs*, void*);
-static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
-static int memdbSleep(sqlite3_vfs*, int microseconds);
-/* static int memdbCurrentTime(sqlite3_vfs*, double*); */
-static int memdbGetLastError(sqlite3_vfs*, int, char *);
-static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
-
-static sqlite3_vfs memdb_vfs = {
- 2, /* iVersion */
- 0, /* szOsFile (set when registered) */
- 1024, /* mxPathname */
- 0, /* pNext */
- "memdb", /* zName */
- 0, /* pAppData (set when registered) */
- memdbOpen, /* xOpen */
- 0, /* memdbDelete, */ /* xDelete */
- memdbAccess, /* xAccess */
- memdbFullPathname, /* xFullPathname */
- memdbDlOpen, /* xDlOpen */
- memdbDlError, /* xDlError */
- memdbDlSym, /* xDlSym */
- memdbDlClose, /* xDlClose */
- memdbRandomness, /* xRandomness */
- memdbSleep, /* xSleep */
- 0, /* memdbCurrentTime, */ /* xCurrentTime */
- memdbGetLastError, /* xGetLastError */
- memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
-};
-
-static const sqlite3_io_methods memdb_io_methods = {
- 3, /* iVersion */
- memdbClose, /* xClose */
- memdbRead, /* xRead */
- memdbWrite, /* xWrite */
- memdbTruncate, /* xTruncate */
- memdbSync, /* xSync */
- memdbFileSize, /* xFileSize */
- memdbLock, /* xLock */
- memdbLock, /* xUnlock - same as xLock in this case */
- 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
- memdbFileControl, /* xFileControl */
- 0, /* memdbSectorSize,*/ /* xSectorSize */
- memdbDeviceCharacteristics, /* xDeviceCharacteristics */
- 0, /* xShmMap */
- 0, /* xShmLock */
- 0, /* xShmBarrier */
- 0, /* xShmUnmap */
- memdbFetch, /* xFetch */
- memdbUnfetch /* xUnfetch */
-};
-
-
-
-/*
-** Close an memdb-file.
-**
-** The pData pointer is owned by the application, so there is nothing
-** to free.
-*/
-static int memdbClose(sqlite3_file *pFile){
- MemFile *p = (MemFile *)pFile;
- if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
- return SQLITE_OK;
-}
-
-/*
-** Read data from an memdb-file.
-*/
-static int memdbRead(
- sqlite3_file *pFile,
- void *zBuf,
- int iAmt,
- sqlite_int64 iOfst
-){
- MemFile *p = (MemFile *)pFile;
- if( iOfst+iAmt>p->sz ){
- memset(zBuf, 0, iAmt);
- if( iOfstsz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
- return SQLITE_IOERR_SHORT_READ;
- }
- memcpy(zBuf, p->aData+iOfst, iAmt);
- return SQLITE_OK;
-}
-
-/*
-** Try to enlarge the memory allocation to hold at least sz bytes
-*/
-static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
- unsigned char *pNew;
- if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
- return SQLITE_FULL;
- }
- if( newSz>p->szMax ){
- return SQLITE_FULL;
- }
- newSz *= 2;
- if( newSz>p->szMax ) newSz = p->szMax;
- pNew = sqlite3_realloc64(p->aData, newSz);
- if( pNew==0 ) return SQLITE_NOMEM;
- p->aData = pNew;
- p->szAlloc = newSz;
- return SQLITE_OK;
-}
-
-/*
-** Write data to an memdb-file.
-*/
-static int memdbWrite(
- sqlite3_file *pFile,
- const void *z,
- int iAmt,
- sqlite_int64 iOfst
-){
- MemFile *p = (MemFile *)pFile;
- if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
- if( iOfst+iAmt>p->sz ){
- int rc;
- if( iOfst+iAmt>p->szAlloc
- && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
- ){
- return rc;
- }
- if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
- p->sz = iOfst+iAmt;
- }
- memcpy(p->aData+iOfst, z, iAmt);
- return SQLITE_OK;
-}
-
-/*
-** Truncate an memdb-file.
-**
-** In rollback mode (which is always the case for memdb, as it does not
-** support WAL mode) the truncate() method is only used to reduce
-** the size of a file, never to increase the size.
-*/
-static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
- MemFile *p = (MemFile *)pFile;
- if( NEVER(size>p->sz) ) return SQLITE_FULL;
- p->sz = size;
- return SQLITE_OK;
-}
-
-/*
-** Sync an memdb-file.
-*/
-static int memdbSync(sqlite3_file *pFile, int flags){
- return SQLITE_OK;
-}
-
-/*
-** Return the current file-size of an memdb-file.
-*/
-static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
- MemFile *p = (MemFile *)pFile;
- *pSize = p->sz;
- return SQLITE_OK;
-}
-
-/*
-** Lock an memdb-file.
-*/
-static int memdbLock(sqlite3_file *pFile, int eLock){
- MemFile *p = (MemFile *)pFile;
- if( eLock>SQLITE_LOCK_SHARED
- && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
- ){
- return SQLITE_READONLY;
- }
- p->eLock = eLock;
- return SQLITE_OK;
-}
-
-#if 0 /* Never used because memdbAccess() always returns false */
-/*
-** Check if another file-handle holds a RESERVED lock on an memdb-file.
-*/
-static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
- *pResOut = 0;
- return SQLITE_OK;
-}
-#endif
-
-/*
-** File control method. For custom operations on an memdb-file.
-*/
-static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
- MemFile *p = (MemFile *)pFile;
- int rc = SQLITE_NOTFOUND;
- if( op==SQLITE_FCNTL_VFSNAME ){
- *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
- rc = SQLITE_OK;
- }
- if( op==SQLITE_FCNTL_SIZE_LIMIT ){
- sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
- if( iLimitsz ){
- if( iLimit<0 ){
- iLimit = p->szMax;
- }else{
- iLimit = p->sz;
- }
- }
- p->szMax = iLimit;
- *(sqlite3_int64*)pArg = iLimit;
- rc = SQLITE_OK;
- }
- return rc;
-}
-
-#if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
-/*
-** Return the sector-size in bytes for an memdb-file.
-*/
-static int memdbSectorSize(sqlite3_file *pFile){
- return 1024;
-}
-#endif
-
-/*
-** Return the device characteristic flags supported by an memdb-file.
-*/
-static int memdbDeviceCharacteristics(sqlite3_file *pFile){
- return SQLITE_IOCAP_ATOMIC |
- SQLITE_IOCAP_POWERSAFE_OVERWRITE |
- SQLITE_IOCAP_SAFE_APPEND |
- SQLITE_IOCAP_SEQUENTIAL;
-}
-
-/* Fetch a page of a memory-mapped file */
-static int memdbFetch(
- sqlite3_file *pFile,
- sqlite3_int64 iOfst,
- int iAmt,
- void **pp
-){
- MemFile *p = (MemFile *)pFile;
- if( iOfst+iAmt>p->sz ){
- *pp = 0;
- }else{
- p->nMmap++;
- *pp = (void*)(p->aData + iOfst);
- }
- return SQLITE_OK;
-}
-
-/* Release a memory-mapped page */
-static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
- MemFile *p = (MemFile *)pFile;
- p->nMmap--;
- return SQLITE_OK;
-}
-
-/*
-** Open an mem file handle.
-*/
-static int memdbOpen(
- sqlite3_vfs *pVfs,
- const char *zName,
- sqlite3_file *pFile,
- int flags,
- int *pOutFlags
-){
- MemFile *p = (MemFile*)pFile;
- if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
- return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
- }
- memset(p, 0, sizeof(*p));
- p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
- assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
- *pOutFlags = flags | SQLITE_OPEN_MEMORY;
- p->base.pMethods = &memdb_io_methods;
- p->szMax = sqlite3GlobalConfig.mxMemdbSize;
- return SQLITE_OK;
-}
-
-#if 0 /* Only used to delete rollback journals, master journals, and WAL
- ** files, none of which exist in memdb. So this routine is never used */
-/*
-** Delete the file located at zPath. If the dirSync argument is true,
-** ensure the file-system modifications are synced to disk before
-** returning.
-*/
-static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
- return SQLITE_IOERR_DELETE;
-}
-#endif
-
-/*
-** Test for access permissions. Return true if the requested permission
-** is available, or false otherwise.
-**
-** With memdb, no files ever exist on disk. So always return false.
-*/
-static int memdbAccess(
- sqlite3_vfs *pVfs,
- const char *zPath,
- int flags,
- int *pResOut
-){
- *pResOut = 0;
- return SQLITE_OK;
-}
-
-/*
-** Populate buffer zOut with the full canonical pathname corresponding
-** to the pathname in zPath. zOut is guaranteed to point to a buffer
-** of at least (INST_MAX_PATHNAME+1) bytes.
-*/
-static int memdbFullPathname(
- sqlite3_vfs *pVfs,
- const char *zPath,
- int nOut,
- char *zOut
-){
- sqlite3_snprintf(nOut, zOut, "%s", zPath);
- return SQLITE_OK;
-}
-
-/*
-** Open the dynamic library located at zPath and return a handle.
-*/
-static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
- return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
-}
-
-/*
-** Populate the buffer zErrMsg (size nByte bytes) with a human readable
-** utf-8 string describing the most recent error encountered associated
-** with dynamic libraries.
-*/
-static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
- ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
-}
-
-/*
-** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
-*/
-static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
- return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
-}
-
-/*
-** Close the dynamic library handle pHandle.
-*/
-static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
- ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
-}
-
-/*
-** Populate the buffer pointed to by zBufOut with nByte bytes of
-** random data.
-*/
-static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
- return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
-}
-
-/*
-** Sleep for nMicro microseconds. Return the number of microseconds
-** actually slept.
-*/
-static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
- return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
-}
-
-#if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
-/*
-** Return the current time as a Julian Day number in *pTimeOut.
-*/
-static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
- return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
-}
-#endif
-
-static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
- return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
-}
-static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
- return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
-}
-
-/*
-** Translate a database connection pointer and schema name into a
-** MemFile pointer.
-*/
-static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
- MemFile *p = 0;
- int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
- if( rc ) return 0;
- if( p->base.pMethods!=&memdb_io_methods ) return 0;
- return p;
-}
-
-/*
-** Return the serialization of a database
-*/
-SQLITE_API unsigned char *sqlite3_serialize(
- sqlite3 *db, /* The database connection */
- const char *zSchema, /* Which database within the connection */
- sqlite3_int64 *piSize, /* Write size here, if not NULL */
- unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
-){
- MemFile *p;
- int iDb;
- Btree *pBt;
- sqlite3_int64 sz;
- int szPage = 0;
- sqlite3_stmt *pStmt = 0;
- unsigned char *pOut;
- char *zSql;
- int rc;
-
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !sqlite3SafetyCheckOk(db) ){
- (void)SQLITE_MISUSE_BKPT;
- return 0;
- }
-#endif
-
- if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
- p = memdbFromDbSchema(db, zSchema);
- iDb = sqlite3FindDbName(db, zSchema);
- if( piSize ) *piSize = -1;
- if( iDb<0 ) return 0;
- if( p ){
- if( piSize ) *piSize = p->sz;
- if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
- pOut = p->aData;
- }else{
- pOut = sqlite3_malloc64( p->sz );
- if( pOut ) memcpy(pOut, p->aData, p->sz);
- }
- return pOut;
- }
- pBt = db->aDb[iDb].pBt;
- if( pBt==0 ) return 0;
- szPage = sqlite3BtreeGetPageSize(pBt);
- zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
- rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
- sqlite3_free(zSql);
- if( rc ) return 0;
- rc = sqlite3_step(pStmt);
- if( rc!=SQLITE_ROW ){
- pOut = 0;
- }else{
- sz = sqlite3_column_int64(pStmt, 0)*szPage;
- if( piSize ) *piSize = sz;
- if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
- pOut = 0;
- }else{
- pOut = sqlite3_malloc64( sz );
- if( pOut ){
- int nPage = sqlite3_column_int(pStmt, 0);
- Pager *pPager = sqlite3BtreePager(pBt);
- int pgno;
- for(pgno=1; pgno<=nPage; pgno++){
- DbPage *pPage = 0;
- unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
- rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
- if( rc==SQLITE_OK ){
- memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
- }else{
- memset(pTo, 0, szPage);
- }
- sqlite3PagerUnref(pPage);
- }
- }
- }
- }
- sqlite3_finalize(pStmt);
- return pOut;
-}
-
-/* Convert zSchema to a MemDB and initialize its content.
-*/
-SQLITE_API int sqlite3_deserialize(
- sqlite3 *db, /* The database connection */
- const char *zSchema, /* Which DB to reopen with the deserialization */
- unsigned char *pData, /* The serialized database content */
- sqlite3_int64 szDb, /* Number bytes in the deserialization */
- sqlite3_int64 szBuf, /* Total size of buffer pData[] */
- unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
-){
- MemFile *p;
- char *zSql;
- sqlite3_stmt *pStmt = 0;
- int rc;
- int iDb;
-
-#ifdef SQLITE_ENABLE_API_ARMOR
- if( !sqlite3SafetyCheckOk(db) ){
- return SQLITE_MISUSE_BKPT;
- }
- if( szDb<0 ) return SQLITE_MISUSE_BKPT;
- if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
-#endif
-
- sqlite3_mutex_enter(db->mutex);
- if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
- iDb = sqlite3FindDbName(db, zSchema);
- if( iDb<0 ){
- rc = SQLITE_ERROR;
- goto end_deserialize;
- }
- zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
- rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
- sqlite3_free(zSql);
- if( rc ) goto end_deserialize;
- db->init.iDb = (u8)iDb;
- db->init.reopenMemdb = 1;
- rc = sqlite3_step(pStmt);
- db->init.reopenMemdb = 0;
- if( rc!=SQLITE_DONE ){
- rc = SQLITE_ERROR;
- goto end_deserialize;
- }
- p = memdbFromDbSchema(db, zSchema);
- if( p==0 ){
- rc = SQLITE_ERROR;
- }else{
- p->aData = pData;
- p->sz = szDb;
- p->szAlloc = szBuf;
- p->szMax = szBuf;
- if( p->szMaxszMax = sqlite3GlobalConfig.mxMemdbSize;
- }
- p->mFlags = mFlags;
- rc = SQLITE_OK;
- }
-
-end_deserialize:
- sqlite3_finalize(pStmt);
- sqlite3_mutex_leave(db->mutex);
- return rc;
-}
-
-/*
-** This routine is called when the extension is loaded.
-** Register the new VFS.
-*/
-SQLITE_PRIVATE int sqlite3MemdbInit(void){
- sqlite3_vfs *pLower = sqlite3_vfs_find(0);
- int sz = pLower->szOsFile;
- memdb_vfs.pAppData = pLower;
- /* In all known configurations of SQLite, the size of a default
- ** sqlite3_file is greater than the size of a memdb sqlite3_file.
- ** Should that ever change, remove the following NEVER() */
- if( NEVER(szBITVEC_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.
-*/
-struct Bitvec {
- u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
- 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. */
- 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. */
- union {
- BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
- u32 aHash[BITVEC_NINT]; /* Hash table representation */
- Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
- } u;
-};
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
- Bitvec *p;
- assert( sizeof(*p)==BITVEC_SZ );
- p = sqlite3MallocZero( sizeof(*p) );
- if( p ){
- 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.
-*/
-SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
- assert( p!=0 );
- i--;
- if( i>=p->iSize ) return 0;
- while( p->iDivisor ){
- u32 bin = i/p->iDivisor;
- i = i%p->iDivisor;
- p = p->u.apSub[bin];
- if (!p) {
- return 0;
- }
- }
- if( p->iSize<=BITVEC_NBIT ){
- return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
- } else{
- u32 h = BITVEC_HASH(i++);
- while( p->u.aHash[h] ){
- if( p->u.aHash[h]==i ) return 1;
- h = (h+1) % BITVEC_NINT;
- }
- return 0;
- }
-}
-SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
- return p!=0 && sqlite3BitvecTestNotNull(p,i);
-}
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
- u32 h;
- if( p==0 ) return SQLITE_OK;
- assert( i>0 );
- assert( i<=p->iSize );
- i--;
- while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
- u32 bin = i/p->iDivisor;
- i = i%p->iDivisor;
- if( p->u.apSub[bin]==0 ){
- p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
- if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
- }
- p = p->u.apSub[bin];
- }
- if( p->iSize<=BITVEC_NBIT ){
- p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (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( !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] );
- /* 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 ){
- unsigned int j;
- int rc;
- u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
- if( aiValues==0 ){
- return SQLITE_NOMEM_BKPT;
- }else{
- memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
- memset(p->u.apSub, 0, sizeof(p->u.apSub));
- p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
- rc = sqlite3BitvecSet(p, i);
- for(j=0; jnSet++;
- 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.
-*/
-SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
- if( p==0 ) return;
- assert( i>0 );
- i--;
- while( p->iDivisor ){
- u32 bin = i/p->iDivisor;
- i = i%p->iDivisor;
- p = p->u.apSub[bin];
- if (!p) {
- return;
- }
- }
- if( p->iSize<=BITVEC_NBIT ){
- p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
- }else{
- unsigned int j;
- u32 *aiValues = pBuf;
- memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
- memset(p->u.aHash, 0, sizeof(p->u.aHash));
- p->nSet = 0;
- for(j=0; jnSet++;
- while( p->u.aHash[h] ){
- h++;
- if( h>=BITVEC_NINT ) h = 0;
- }
- p->u.aHash[h] = aiValues[j];
- }
- }
- }
-}
-
-/*
-** Destroy a bitmap object. Reclaim all memory used.
-*/
-SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
- if( p==0 ) return;
- if( p->iDivisor ){
- unsigned int i;
- for(i=0; iu.apSub[i]);
- }
- }
- sqlite3_free(p);
-}
-
-/*
-** Return the value of the iSize parameter specified when Bitvec *p
-** was created.
-*/
-SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
- return p->iSize;
-}
-
-#ifndef SQLITE_UNTESTABLE
-/*
-** 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))
-#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
-#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=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.
-*/
-SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
- Bitvec *pBitvec = 0;
- unsigned char *pV = 0;
- int rc = -1;
- int i, nx, pc, op;
- void *pTmpSpace;
-
- /* Allocate the Bitvec to be tested and a linear array of
- ** bits to act as the reference */
- pBitvec = sqlite3BitvecCreate( sz );
- pV = sqlite3MallocZero( (sz+7)/8 + 1 );
- pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
- if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
-
- /* NULL pBitvec tests */
- sqlite3BitvecSet(0, 1);
- sqlite3BitvecClear(0, 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;
- sqlite3_randomness(sizeof(i), &i);
- break;
- }
- }
- if( (--aOp[pc+1]) > 0 ) nx = 0;
- pc += nx;
- i = (i & 0x7fffffff)%sz;
- if( (op & 1)!=0 ){
- SETBIT(pV, (i+1));
- if( op!=5 ){
- if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
- }
- }else{
- CLEARBIT(pV, (i+1));
- sqlite3BitvecClear(pBitvec, 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(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
- + sqlite3BitvecTest(pBitvec, 0)
- + (sqlite3BitvecSize(pBitvec) - sz);
- for(i=1; i<=sz; i++){
- if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
- rc = i;
- break;
- }
- }
-
- /* Free allocated structure */
-bitvec_end:
- sqlite3_free(pTmpSpace);
- sqlite3_free(pV);
- sqlite3BitvecDestroy(pBitvec);
- return rc;
-}
-#endif /* SQLITE_UNTESTABLE */
-
-/************** End of bitvec.c **********************************************/
-/************** Begin file pcache.c ******************************************/
-/*
-** 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 file implements that page cache.
-*/
-/* #include "sqliteInt.h" */
-
-/*
-** A complete page cache is an instance of this structure. Every
-** entry in the cache holds a single page of the database file. The
-** btree layer only operates on the cached copy of the database pages.
-**
-** A page cache entry is "clean" if it exactly matches what is currently
-** on disk. A page is "dirty" if it has been modified and needs to be
-** persisted to disk.
-**
-** pDirty, pDirtyTail, pSynced:
-** All dirty pages are linked into the doubly linked list using
-** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
-** such that p was added to the list more recently than p->pDirtyNext.
-** PCache.pDirty points to the first (newest) element in the list and
-** pDirtyTail to the last (oldest).
-**
-** The PCache.pSynced variable is used to optimize searching for a dirty
-** page to eject from the cache mid-transaction. It is better to eject
-** a page that does not require a journal sync than one that does.
-** Therefore, pSynced is maintained so that it *almost* always points
-** to either the oldest page in the pDirty/pDirtyTail list that has a
-** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
-** (so that the right page to eject can be found by following pDirtyPrev
-** pointers).
-*/
-struct PCache {
- PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
- PgHdr *pSynced; /* Last synced page in dirty page list */
- int nRefSum; /* Sum of ref counts over all pages */
- int szCache; /* Configured cache size */
- int szSpill; /* Size before spilling occurs */
- int szPage; /* Size of every page in this cache */
- int szExtra; /* Size of extra space for each page */
- u8 bPurgeable; /* True if pages are on backing store */
- u8 eCreate; /* eCreate value for for xFetch() */
- int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
- void *pStress; /* Argument to xStress */
- sqlite3_pcache *pCache; /* Pluggable cache module */
-};
-
-/********************************** Test and Debug Logic **********************/
-/*
-** Debug tracing macros. Enable by by changing the "0" to "1" and
-** recompiling.
-**
-** When sqlite3PcacheTrace is 1, single line trace messages are issued.
-** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
-** is displayed for many operations, resulting in a lot of output.
-*/
-#if defined(SQLITE_DEBUG) && 0
- int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
- int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
-# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
- void pcacheDump(PCache *pCache){
- int N;
- int i, j;
- sqlite3_pcache_page *pLower;
- PgHdr *pPg;
- unsigned char *a;
-
- if( sqlite3PcacheTrace<2 ) return;
- if( pCache->pCache==0 ) return;
- N = sqlite3PcachePagecount(pCache);
- if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
- for(i=1; i<=N; i++){
- pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
- if( pLower==0 ) continue;
- pPg = (PgHdr*)pLower->pExtra;
- printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
- a = (unsigned char *)pLower->pBuf;
- for(j=0; j<12; j++) printf("%02x", a[j]);
- printf("\n");
- if( pPg->pPage==0 ){
- sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
- }
- }
- }
- #else
-# define pcacheTrace(X)
-# define pcacheDump(X)
-#endif
-
-/*
-** Check invariants on a PgHdr entry. Return true if everything is OK.
-** Return false if any invariant is violated.
-**
-** This routine is for use inside of assert() statements only. For
-** example:
-**
-** assert( sqlite3PcachePageSanity(pPg) );
-*/
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
- PCache *pCache;
- assert( pPg!=0 );
- assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
- pCache = pPg->pCache;
- assert( pCache!=0 ); /* Every page has an associated PCache */
- if( pPg->flags & PGHDR_CLEAN ){
- assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
- assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
- assert( pCache->pDirtyTail!=pPg );
- }
- /* WRITEABLE pages must also be DIRTY */
- if( pPg->flags & PGHDR_WRITEABLE ){
- assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
- }
- /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
- ** for example, when using the sqlite3PagerDontWrite() optimization:
- ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
- ** (2) Page X moved to freelist, WRITEABLE is cleared
- ** (3) Page X reused, WRITEABLE is set again
- ** If NEED_SYNC had been cleared in step 2, then it would not be reset
- ** in step 3, and page might be written into the database without first
- ** syncing the rollback journal, which might cause corruption on a power
- ** loss.
- **
- ** Another example is when the database page size is smaller than the
- ** disk sector size. When any page of a sector is journalled, all pages
- ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
- ** in case they are later modified, since all pages in the same sector
- ** must be journalled and synced before any of those pages can be safely
- ** written.
- */
- return 1;
-}
-#endif /* SQLITE_DEBUG */
-
-
-/********************************** Linked List Management ********************/
-
-/* Allowed values for second argument to pcacheManageDirtyList() */
-#define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
-#define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
-#define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
-
-/*
-** Manage pPage's participation on the dirty list. Bits of the addRemove
-** argument determines what operation to do. The 0x01 bit means first
-** remove pPage from the dirty list. The 0x02 means add pPage back to
-** the dirty list. Doing both moves pPage to the front of the dirty list.
-*/
-static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
- PCache *p = pPage->pCache;
-
- pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
- addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
- pPage->pgno));
- if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
- assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
- assert( pPage->pDirtyPrev || pPage==p->pDirty );
-
- /* Update the PCache1.pSynced variable if necessary. */
- if( p->pSynced==pPage ){
- p->pSynced = pPage->pDirtyPrev;
- }
-
- if( pPage->pDirtyNext ){
- pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
- }else{
- assert( pPage==p->pDirtyTail );
- p->pDirtyTail = pPage->pDirtyPrev;
- }
- if( pPage->pDirtyPrev ){
- pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
- }else{
- /* If there are now no dirty pages in the cache, set eCreate to 2.
- ** This is an optimization that allows sqlite3PcacheFetch() to skip
- ** searching for a dirty page to eject from the cache when it might
- ** otherwise have to. */
- assert( pPage==p->pDirty );
- p->pDirty = pPage->pDirtyNext;
- assert( p->bPurgeable || p->eCreate==2 );
- if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
- assert( p->bPurgeable==0 || p->eCreate==1 );
- p->eCreate = 2;
- }
- }
- }
- if( addRemove & PCACHE_DIRTYLIST_ADD ){
- pPage->pDirtyPrev = 0;
- pPage->pDirtyNext = p->pDirty;
- if( pPage->pDirtyNext ){
- assert( pPage->pDirtyNext->pDirtyPrev==0 );
- pPage->pDirtyNext->pDirtyPrev = pPage;
- }else{
- p->pDirtyTail = pPage;
- if( p->bPurgeable ){
- assert( p->eCreate==2 );
- p->eCreate = 1;
- }
- }
- p->pDirty = pPage;
-
- /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
- ** pSynced to point to it. Checking the NEED_SYNC flag is an
- ** optimization, as if pSynced points to a page with the NEED_SYNC
- ** flag set sqlite3PcacheFetchStress() searches through all newer
- ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
- if( !p->pSynced
- && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
- ){
- p->pSynced = pPage;
- }
- }
- pcacheDump(p);
-}
-
-/*
-** Wrapper around the pluggable caches xUnpin method. If the cache is
-** being used for an in-memory database, this function is a no-op.
-*/
-static void pcacheUnpin(PgHdr *p){
- if( p->pCache->bPurgeable ){
- pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
- sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
- pcacheDump(p->pCache);
- }
-}
-
-/*
-** Compute the number of pages of cache requested. p->szCache is the
-** cache size requested by the "PRAGMA cache_size" statement.
-*/
-static int numberOfCachePages(PCache *p){
- if( p->szCache>=0 ){
- /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
- ** suggested cache size is set to N. */
- return p->szCache;
- }else{
- /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
- ** number of cache pages is adjusted to be a number of pages that would
- ** use approximately abs(N*1024) bytes of memory based on the current
- ** page size. */
- return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
- }
-}
-
-/*************************************************** General Interfaces ******
-**
-** Initialize and shutdown the page cache subsystem. Neither of these
-** functions are threadsafe.
-*/
-SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
- if( sqlite3GlobalConfig.pcache2.xInit==0 ){
- /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
- ** built-in default page cache is used instead of the application defined
- ** page cache. */
- sqlite3PCacheSetDefault();
- }
- return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
-}
-SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
- if( sqlite3GlobalConfig.pcache2.xShutdown ){
- /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
- sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
- }
-}
-
-/*
-** Return the size in bytes of a PCache object.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
-
-/*
-** Create a new PCache object. Storage space to hold the object
-** has already been allocated and is passed in as the p pointer.
-** The caller discovers how much space needs to be allocated by
-** calling sqlite3PcacheSize().
-**
-** szExtra is some extra space allocated for each page. The first
-** 8 bytes of the extra space will be zeroed as the page is allocated,
-** but remaining content will be uninitialized. Though it is opaque
-** to this module, the extra space really ends up being the MemPage
-** structure in the pager.
-*/
-SQLITE_PRIVATE int 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 *p /* Preallocated space for the PCache */
-){
- memset(p, 0, sizeof(PCache));
- p->szPage = 1;
- p->szExtra = szExtra;
- assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
- p->bPurgeable = bPurgeable;
- p->eCreate = 2;
- p->xStress = xStress;
- p->pStress = pStress;
- p->szCache = 100;
- p->szSpill = 1;
- pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
- return sqlite3PcacheSetPageSize(p, szPage);
-}
-
-/*
-** Change the page size for PCache object. The caller must ensure that there
-** are no outstanding page references when this function is called.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
- assert( pCache->nRefSum==0 && pCache->pDirty==0 );
- if( pCache->szPage ){
- sqlite3_pcache *pNew;
- pNew = sqlite3GlobalConfig.pcache2.xCreate(
- szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
- pCache->bPurgeable
- );
- if( pNew==0 ) return SQLITE_NOMEM_BKPT;
- sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
- if( pCache->pCache ){
- sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
- }
- pCache->pCache = pNew;
- pCache->szPage = szPage;
- pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
- }
- return SQLITE_OK;
-}
-
-/*
-** Try to obtain a page from the cache.
-**
-** This routine returns a pointer to an sqlite3_pcache_page object if
-** such an object is already in cache, or if a new one is created.
-** This routine returns a NULL pointer if the object was not in cache
-** and could not be created.
-**
-** The createFlags should be 0 to check for existing pages and should
-** be 3 (not 1, but 3) to try to create a new page.
-**
-** If the createFlag is 0, then NULL is always returned if the page
-** is not already in the cache. If createFlag is 1, then a new page
-** is created only if that can be done without spilling dirty pages
-** and without exceeding the cache size limit.
-**
-** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
-** initialize the sqlite3_pcache_page object and convert it into a
-** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
-** routines are split this way for performance reasons. When separated
-** they can both (usually) operate without having to push values to
-** the stack on entry and pop them back off on exit, which saves a
-** lot of pushing and popping.
-*/
-SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
- PCache *pCache, /* Obtain the page from this cache */
- Pgno pgno, /* Page number to obtain */
- int createFlag /* If true, create page if it does not exist already */
-){
- int eCreate;
- sqlite3_pcache_page *pRes;
-
- assert( pCache!=0 );
- assert( pCache->pCache!=0 );
- assert( createFlag==3 || createFlag==0 );
- assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
-
- /* eCreate defines what to do if the page does not exist.
- ** 0 Do not allocate a new page. (createFlag==0)
- ** 1 Allocate a new page if doing so is inexpensive.
- ** (createFlag==1 AND bPurgeable AND pDirty)
- ** 2 Allocate a new page even it doing so is difficult.
- ** (createFlag==1 AND !(bPurgeable AND pDirty)
- */
- eCreate = createFlag & pCache->eCreate;
- assert( eCreate==0 || eCreate==1 || eCreate==2 );
- assert( createFlag==0 || pCache->eCreate==eCreate );
- assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
- pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
- pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
- createFlag?" create":"",pRes));
- return pRes;
-}
-
-/*
-** If the sqlite3PcacheFetch() routine is unable to allocate a new
-** page because no clean pages are available for reuse and the cache
-** size limit has been reached, then this routine can be invoked to
-** try harder to allocate a page. This routine might invoke the stress
-** callback to spill dirty pages to the journal. It will then try to
-** allocate the new page and will only fail to allocate a new page on
-** an OOM error.
-**
-** This routine should be invoked only after sqlite3PcacheFetch() fails.
-*/
-SQLITE_PRIVATE int sqlite3PcacheFetchStress(
- PCache *pCache, /* Obtain the page from this cache */
- Pgno pgno, /* Page number to obtain */
- sqlite3_pcache_page **ppPage /* Write result here */
-){
- PgHdr *pPg;
- if( pCache->eCreate==2 ) return 0;
-
- if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
- /* 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 the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
- ** flag is currently referenced, then the following may leave pSynced
- ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
- ** cleared). This is Ok, as pSynced is just an optimization. */
- for(pPg=pCache->pSynced;
- pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
- pPg=pPg->pDirtyPrev
- );
- pCache->pSynced = pPg;
- if( !pPg ){
- for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
- }
- if( pPg ){
- int rc;
-#ifdef SQLITE_LOG_CACHE_SPILL
- sqlite3_log(SQLITE_FULL,
- "spill page %d making room for %d - cache used: %d/%d",
- pPg->pgno, pgno,
- sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
- numberOfCachePages(pCache));
-#endif
- pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
- rc = pCache->xStress(pCache->pStress, pPg);
- pcacheDump(pCache);
- if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
- return rc;
- }
- }
- }
- *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
- return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
-}
-
-/*
-** This is a helper routine for sqlite3PcacheFetchFinish()
-**
-** In the uncommon case where the page being fetched has not been
-** initialized, this routine is invoked to do the initialization.
-** This routine is broken out into a separate function since it
-** requires extra stack manipulation that can be avoided in the common
-** case.
-*/
-static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
- PCache *pCache, /* Obtain the page from this cache */
- Pgno pgno, /* Page number obtained */
- sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
-){
- PgHdr *pPgHdr;
- assert( pPage!=0 );
- pPgHdr = (PgHdr*)pPage->pExtra;
- assert( pPgHdr->pPage==0 );
- memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
- pPgHdr->pPage = pPage;
- pPgHdr->pData = pPage->pBuf;
- pPgHdr->pExtra = (void *)&pPgHdr[1];
- memset(pPgHdr->pExtra, 0, 8);
- pPgHdr->pCache = pCache;
- pPgHdr->pgno = pgno;
- pPgHdr->flags = PGHDR_CLEAN;
- return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
-}
-
-/*
-** This routine converts the sqlite3_pcache_page object returned by
-** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
-** must be called after sqlite3PcacheFetch() in order to get a usable
-** result.
-*/
-SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
- PCache *pCache, /* Obtain the page from this cache */
- Pgno pgno, /* Page number obtained */
- sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
-){
- PgHdr *pPgHdr;
-
- assert( pPage!=0 );
- pPgHdr = (PgHdr *)pPage->pExtra;
-
- if( !pPgHdr->pPage ){
- return pcacheFetchFinishWithInit(pCache, pgno, pPage);
- }
- pCache->nRefSum++;
- pPgHdr->nRef++;
- assert( sqlite3PcachePageSanity(pPgHdr) );
- return pPgHdr;
-}
-
-/*
-** Decrement the reference count on a page. If the page is clean and the
-** reference count drops to 0, then it is made eligible for recycling.
-*/
-SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
- assert( p->nRef>0 );
- p->pCache->nRefSum--;
- if( (--p->nRef)==0 ){
- if( p->flags&PGHDR_CLEAN ){
- pcacheUnpin(p);
- }else{
- pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
- }
- }
-}
-
-/*
-** Increase the reference count of a supplied page by 1.
-*/
-SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
- assert(p->nRef>0);
- assert( sqlite3PcachePageSanity(p) );
- p->nRef++;
- p->pCache->nRefSum++;
-}
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
- assert( p->nRef==1 );
- assert( sqlite3PcachePageSanity(p) );
- if( p->flags&PGHDR_DIRTY ){
- pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
- }
- p->pCache->nRefSum--;
- sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
-}
-
-/*
-** Make sure the page is marked as dirty. If it isn't dirty already,
-** make it so.
-*/
-SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
- assert( p->nRef>0 );
- assert( sqlite3PcachePageSanity(p) );
- if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
- p->flags &= ~PGHDR_DONT_WRITE;
- if( p->flags & PGHDR_CLEAN ){
- p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
- pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
- assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
- pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
- }
- assert( sqlite3PcachePageSanity(p) );
- }
-}
-
-/*
-** Make sure the page is marked as clean. If it isn't clean already,
-** make it so.
-*/
-SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
- assert( sqlite3PcachePageSanity(p) );
- assert( (p->flags & PGHDR_DIRTY)!=0 );
- assert( (p->flags & PGHDR_CLEAN)==0 );
- pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
- p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
- p->flags |= PGHDR_CLEAN;
- pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
- assert( sqlite3PcachePageSanity(p) );
- if( p->nRef==0 ){
- pcacheUnpin(p);
- }
-}
-
-/*
-** Make every page in the cache clean.
-*/
-SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
- PgHdr *p;
- pcacheTrace(("%p.CLEAN-ALL\n",pCache));
- while( (p = pCache->pDirty)!=0 ){
- sqlite3PcacheMakeClean(p);
- }
-}
-
-/*
-** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
-*/
-SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
- PgHdr *p;
- pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
- for(p=pCache->pDirty; p; p=p->pDirtyNext){
- p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
- }
- pCache->pSynced = pCache->pDirtyTail;
-}
-
-/*
-** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
-*/
-SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
- PgHdr *p;
- for(p=pCache->pDirty; p; p=p->pDirtyNext){
- p->flags &= ~PGHDR_NEED_SYNC;
- }
- pCache->pSynced = pCache->pDirtyTail;
-}
-
-/*
-** Change the page number of page p to newPgno.
-*/
-SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
- PCache *pCache = p->pCache;
- assert( p->nRef>0 );
- assert( newPgno>0 );
- assert( sqlite3PcachePageSanity(p) );
- pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
- sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
- p->pgno = newPgno;
- if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
- pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
- }
-}
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
- if( pCache->pCache ){
- PgHdr *p;
- PgHdr *pNext;
- pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
- for(p=pCache->pDirty; p; 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.
- */
- assert( p->pgno>0 );
- if( p->pgno>pgno ){
- assert( p->flags&PGHDR_DIRTY );
- sqlite3PcacheMakeClean(p);
- }
- }
- if( pgno==0 && pCache->nRefSum ){
- sqlite3_pcache_page *pPage1;
- pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
- if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
- ** pCache->nRefSum>0 */
- memset(pPage1->pBuf, 0, pCache->szPage);
- pgno = 1;
- }
- }
- sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
- }
-}
-
-/*
-** Close a cache.
-*/
-SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
- assert( pCache->pCache!=0 );
- pcacheTrace(("%p.CLOSE\n",pCache));
- sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
-}
-
-/*
-** Discard the contents of the cache.
-*/
-SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
- sqlite3PcacheTruncate(pCache, 0);
-}
-
-/*
-** Merge two lists of pages connected by pDirty and in pgno order.
-** Do not bother fixing the pDirtyPrev pointers.
-*/
-static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
- PgHdr result, *pTail;
- pTail = &result;
- assert( pA!=0 && pB!=0 );
- for(;;){
- if( pA->pgnopgno ){
- pTail->pDirty = pA;
- pTail = pA;
- pA = pA->pDirty;
- if( pA==0 ){
- pTail->pDirty = pB;
- break;
- }
- }else{
- pTail->pDirty = pB;
- pTail = pB;
- pB = pB->pDirty;
- if( pB==0 ){
- pTail->pDirty = pA;
- break;
- }
- }
- }
- 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
-static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
- PgHdr *a[N_SORT_BUCKET], *p;
- int i;
- memset(a, 0, sizeof(a));
- while( pIn ){
- p = pIn;
- pIn = p->pDirty;
- p->pDirty = 0;
- for(i=0; ALWAYS(ipDirty; p; p=p->pDirtyNext){
- p->pDirty = p->pDirtyNext;
- }
- return pcacheSortDirtyList(pCache->pDirty);
-}
-
-/*
-** Return the total number of references to all pages held by the cache.
-**
-** This is not the total number of pages referenced, but the sum of the
-** reference count for all pages.
-*/
-SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
- return pCache->nRefSum;
-}
-
-/*
-** Return the number of references to the page supplied as an argument.
-*/
-SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
- return p->nRef;
-}
-
-/*
-** Return the total number of pages in the cache.
-*/
-SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
- assert( pCache->pCache!=0 );
- return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
-}
-
-#ifdef SQLITE_TEST
-/*
-** Get the suggested cache-size value.
-*/
-SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
- return numberOfCachePages(pCache);
-}
-#endif
-
-/*
-** Set the suggested cache-size value.
-*/
-SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
- assert( pCache->pCache!=0 );
- pCache->szCache = mxPage;
- sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
- numberOfCachePages(pCache));
-}
-
-/*
-** Set the suggested cache-spill value. Make no changes if if the
-** argument is zero. Return the effective cache-spill size, which will
-** be the larger of the szSpill and szCache.
-*/
-SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
- int res;
- assert( p->pCache!=0 );
- if( mxPage ){
- if( mxPage<0 ){
- mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
- }
- p->szSpill = mxPage;
- }
- res = numberOfCachePages(p);
- if( resszSpill ) res = p->szSpill;
- return res;
-}
-
-/*
-** Free up as much memory as possible from the page cache.
-*/
-SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
- assert( pCache->pCache!=0 );
- sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
-}
-
-/*
-** Return the size of the header added by this middleware layer
-** in the page-cache hierarchy.
-*/
-SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
-
-/*
-** Return the number of dirty pages currently in the cache, as a percentage
-** of the configured cache size.
-*/
-SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
- PgHdr *pDirty;
- int nDirty = 0;
- int nCache = numberOfCachePages(pCache);
- for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
- return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
-}
-
-#ifdef SQLITE_DIRECT_OVERFLOW_READ
-/*
-** Return true if there are one or more dirty pages in the cache. Else false.
-*/
-SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
- return (pCache->pDirty!=0);
-}
-#endif
-
-#if defined(SQLITE_CHECK_PAGES) || defined(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.
-*/
-SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
- PgHdr *pDirty;
- for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
- xIter(pDirty);
- }
-}
-#endif
-
-/************** End of pcache.c **********************************************/
-/************** Begin file pcache1.c *****************************************/
-/*
-** 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 overridden, then neither of
-** these two features are available.
-**
-** A Page cache line looks like this:
-**
-** -------------------------------------------------------------
-** | database page content | PgHdr1 | MemPage | PgHdr |
-** -------------------------------------------------------------
-**
-** The database page content is up front (so that buffer overreads tend to
-** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
-** is the extension added by the btree.c module containing information such
-** as the database page number and how that database page is used. PgHdr
-** is added by the pcache.c layer and contains information used to keep track
-** of which pages are "dirty". PgHdr1 is an extension added by this
-** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
-** PgHdr1 contains information needed to look up a page by its page number.
-** The superclass sqlite3_pcache_page.pBuf points to the start of the
-** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
-**
-** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
-** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
-** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
-** size can vary according to architecture, compile-time options, and
-** SQLite library version number.
-**
-** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
-** using a separate memory allocation from the database page content. This
-** seeks to overcome the "clownshoe" problem (also called "internal
-** fragmentation" in academic literature) of allocating a few bytes more
-** than a power of two with the memory allocator rounding up to the next
-** power of two, and leaving the rounded-up space unused.
-**
-** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
-** with this module. Information is passed back and forth as PgHdr1 pointers.
-**
-** The pcache.c and pager.c modules deal pointers to PgHdr objects.
-** The btree.c module deals with pointers to MemPage objects.
-**
-** SOURCE OF PAGE CACHE MEMORY:
-**
-** Memory for a page might come from any of three sources:
-**
-** (1) The general-purpose memory allocator - sqlite3Malloc()
-** (2) Global page-cache memory provided using sqlite3_config() with
-** SQLITE_CONFIG_PAGECACHE.
-** (3) PCache-local bulk allocation.
-**
-** The third case is a chunk of heap memory (defaulting to 100 pages worth)
-** that is allocated when the page cache is created. The size of the local
-** bulk allocation can be adjusted using
-**
-** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
-**
-** If N is positive, then N pages worth of memory are allocated using a single
-** sqlite3Malloc() call and that memory is used for the first N pages allocated.
-** Or if N is negative, then -1024*N bytes of memory are allocated and used
-** for as many pages as can be accomodated.
-**
-** Only one of (2) or (3) can be used. Once the memory available to (2) or
-** (3) is exhausted, subsequent allocations fail over to the general-purpose
-** memory allocator (1).
-**
-** Earlier versions of SQLite used only methods (1) and (2). But experiments
-** show that method (3) with N==100 provides about a 5% performance boost for
-** common workloads.
-*/
-/* #include "sqliteInt.h" */
-
-typedef struct PCache1 PCache1;
-typedef struct PgHdr1 PgHdr1;
-typedef struct PgFreeslot PgFreeslot;
-typedef struct PGroup PGroup;
-
-/*
-** Each cache entry is represented by an instance of the following
-** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
-** PgHdr1.pCache->szPage bytes is allocated directly before this structure
-** in memory.
-**
-** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
-** but causes a 2-byte gap in the structure for most architectures (since
-** pointers must be either 4 or 8-byte aligned). As this structure is located
-** in memory directly after the associated page data, if the database is
-** corrupt, code at the b-tree layer may overread the page buffer and
-** read part of this structure before the corruption is detected. This
-** can cause a valgrind error if the unitialized gap is accessed. Using u16
-** ensures there is no such gap, and therefore no bytes of unitialized memory
-** in the structure.
-*/
-struct PgHdr1 {
- sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
- unsigned int iKey; /* Key value (page number) */
- u16 isBulkLocal; /* This page from bulk local storage */
- u16 isAnchor; /* This is the PGroup.lru element */
- PgHdr1 *pNext; /* Next in hash table chain */
- PCache1 *pCache; /* Cache that currently owns this page */
- PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
- PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
- /* NB: pLruPrev is only valid if pLruNext!=0 */
-};
-
-/*
-** A page is pinned if it is not on the LRU list. To be "pinned" means
-** that the page is in active use and must not be deallocated.
-*/
-#define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
-#define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
-
-/* 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 other's 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 recycles pages more efficiently.
-**
-** 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.
-*/
-struct PGroup {
- sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
- unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
- unsigned int nMinPage; /* Sum of nMin for purgeable caches */
- unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
- unsigned int nPurgeable; /* Number of purgeable pages allocated */
- PgHdr1 lru; /* The beginning and end of the LRU list */
-};
-
-/* 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.
-*/
-struct PCache1 {
- /* Cache configuration parameters. Page size (szPage) and the purgeable
- ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
- ** cache is created and are never changed thereafter. nMax may be
- ** modified at any time by a call to the pcache1Cachesize() method.
- ** The PGroup mutex must be held when accessing nMax.
- */
- PGroup *pGroup; /* PGroup this cache belongs to */
- unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
- int szPage; /* Size of database content section */
- int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
- int szAlloc; /* Total size of one pcache line */
- int bPurgeable; /* True if cache is purgeable */
- unsigned int nMin; /* Minimum number of pages reserved */
- unsigned int nMax; /* Configured "cache_size" value */
- unsigned int n90pct; /* nMax*9/10 */
- unsigned int iMaxKey; /* Largest key seen since xTruncate() */
- unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
-
- /* Hash table of all pages. The following variables may only be accessed
- ** when the accessor is holding the PGroup mutex.
- */
- unsigned int nRecyclable; /* Number of pages in the LRU list */
- unsigned int nPage; /* Total number of pages in apHash */
- unsigned int nHash; /* Number of slots in apHash[] */
- PgHdr1 **apHash; /* Hash table for fast lookup by key */
- PgHdr1 *pFree; /* List of unused pcache-local pages */
- void *pBulk; /* Bulk memory used by pcache-local */
-};
-
-/*
-** Free slots in the allocator used to divide up the global page cache
-** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
-*/
-struct PgFreeslot {
- PgFreeslot *pNext; /* Next free slot */
-};
-
-/*
-** Global data used by this cache.
-*/
-static SQLITE_WSD struct PCacheGlobal {
- 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.
- */
- int isInit; /* True if initialized */
- int separateCache; /* Use a new PGroup for each PCache */
- int nInitPage; /* Initial bulk allocation size */
- int szSlot; /* Size of each free slot */
- int nSlot; /* The number of pcache slots */
- int nReserve; /* Try to keep nFreeSlot above this */
- void *pStart, *pEnd; /* Bounds of global page cache memory */
- /* Above requires no mutex. Use mutex below for variable that follow. */
- sqlite3_mutex *mutex; /* Mutex for accessing the following: */
- PgFreeslot *pFree; /* Free page blocks */
- int nFreeSlot; /* Number of unused pcache slots */
- /* 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. */
- int bUnderPressure; /* True if low on PAGECACHE memory */
-} pcache1_g;
-
-/*
-** 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))
-
-/*
-** Macros to enter and leave the PCache LRU mutex.
-*/
-#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
-# define pcache1EnterMutex(X) assert((X)->mutex==0)
-# define pcache1LeaveMutex(X) assert((X)->mutex==0)
-# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
-#else
-# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
-# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
-# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
-#endif
-
-/******************************************************************************/
-/******** 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.
-*/
-SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
- if( pcache1.isInit ){
- PgFreeslot *p;
- if( pBuf==0 ) sz = n = 0;
- if( n==0 ) sz = 0;
- sz = ROUNDDOWN8(sz);
- pcache1.szSlot = sz;
- pcache1.nSlot = pcache1.nFreeSlot = n;
- pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
- pcache1.pStart = pBuf;
- pcache1.pFree = 0;
- pcache1.bUnderPressure = 0;
- while( n-- ){
- p = (PgFreeslot*)pBuf;
- p->pNext = pcache1.pFree;
- pcache1.pFree = p;
- pBuf = (void*)&((char*)pBuf)[sz];
- }
- pcache1.pEnd = pBuf;
- }
-}
-
-/*
-** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
-** true if pCache->pFree ends up containing one or more free pages.
-*/
-static int pcache1InitBulk(PCache1 *pCache){
- i64 szBulk;
- char *zBulk;
- if( pcache1.nInitPage==0 ) return 0;
- /* Do not bother with a bulk allocation if the cache size very small */
- if( pCache->nMax<3 ) return 0;
- sqlite3BeginBenignMalloc();
- if( pcache1.nInitPage>0 ){
- szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
- }else{
- szBulk = -1024 * (i64)pcache1.nInitPage;
- }
- if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
- szBulk = pCache->szAlloc*(i64)pCache->nMax;
- }
- zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
- sqlite3EndBenignMalloc();
- if( zBulk ){
- int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
- do{
- PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
- pX->page.pBuf = zBulk;
- pX->page.pExtra = &pX[1];
- pX->isBulkLocal = 1;
- pX->isAnchor = 0;
- pX->pNext = pCache->pFree;
- pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
- pCache->pFree = pX;
- zBulk += pCache->szAlloc;
- }while( --nBulk );
- }
- return pCache->pFree!=0;
-}
-
-/*
-** 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 void *pcache1Alloc(int nByte){
- void *p = 0;
- assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
- if( nByte<=pcache1.szSlot ){
- sqlite3_mutex_enter(pcache1.mutex);
- p = (PgHdr1 *)pcache1.pFree;
- if( p ){
- pcache1.pFree = pcache1.pFree->pNext;
- pcache1.nFreeSlot--;
- pcache1.bUnderPressure = pcache1.nFreeSlot=0 );
- sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
- sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
- }
- sqlite3_mutex_leave(pcache1.mutex);
- }
- if( p==0 ){
- /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
- ** it from sqlite3Malloc instead.
- */
- p = sqlite3Malloc(nByte);
-#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
- if( p ){
- int sz = sqlite3MallocSize(p);
- sqlite3_mutex_enter(pcache1.mutex);
- sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
- sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
- sqlite3_mutex_leave(pcache1.mutex);
- }
-#endif
- sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
- }
- return p;
-}
-
-/*
-** Free an allocated buffer obtained from pcache1Alloc().
-*/
-static void pcache1Free(void *p){
- if( p==0 ) return;
- if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
- PgFreeslot *pSlot;
- sqlite3_mutex_enter(pcache1.mutex);
- sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
- pSlot = (PgFreeslot*)p;
- pSlot->pNext = pcache1.pFree;
- pcache1.pFree = pSlot;
- pcache1.nFreeSlot++;
- pcache1.bUnderPressure = pcache1.nFreeSlot=pcache1.pStart && ppGroup->mutex) );
- if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
- p = pCache->pFree;
- pCache->pFree = p->pNext;
- p->pNext = 0;
- }else{
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
- /* The group mutex must be released before pcache1Alloc() is called. This
- ** is because it might call sqlite3_release_memory(), which assumes that
- ** this mutex is not held. */
- assert( pcache1.separateCache==0 );
- assert( pCache->pGroup==&pcache1.grp );
- pcache1LeaveMutex(pCache->pGroup);
-#endif
- if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
-#ifdef SQLITE_PCACHE_SEPARATE_HEADER
- pPg = pcache1Alloc(pCache->szPage);
- p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
- if( !pPg || !p ){
- pcache1Free(pPg);
- sqlite3_free(p);
- pPg = 0;
- }
-#else
- pPg = pcache1Alloc(pCache->szAlloc);
- p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
-#endif
- if( benignMalloc ){ sqlite3EndBenignMalloc(); }
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
- pcache1EnterMutex(pCache->pGroup);
-#endif
- if( pPg==0 ) return 0;
- p->page.pBuf = pPg;
- p->page.pExtra = &p[1];
- p->isBulkLocal = 0;
- p->isAnchor = 0;
- }
- (*pCache->pnPurgeable)++;
- return p;
-}
-
-/*
-** Free a page object allocated by pcache1AllocPage().
-*/
-static void pcache1FreePage(PgHdr1 *p){
- PCache1 *pCache;
- assert( p!=0 );
- pCache = p->pCache;
- assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
- if( p->isBulkLocal ){
- p->pNext = pCache->pFree;
- pCache->pFree = p;
- }else{
- pcache1Free(p->page.pBuf);
-#ifdef SQLITE_PCACHE_SEPARATE_HEADER
- sqlite3_free(p);
-#endif
- }
- (*pCache->pnPurgeable)--;
-}
-
-/*
-** Malloc function used by SQLite to obtain space from the buffer configured
-** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
-** exists, this function falls back to sqlite3Malloc().
-*/
-SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
- assert( sz<=65536+8 ); /* These allocations are never very large */
- return pcache1Alloc(sz);
-}
-
-/*
-** Free an allocated buffer obtained from sqlite3PageMalloc().
-*/
-SQLITE_PRIVATE void sqlite3PageFree(void *p){
- pcache1Free(p);
-}
-
-
-/*
-** Return true if it desirable to avoid allocating a new page cache
-** entry.
-**
-** If memory was allocated specifically to the page cache using
-** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
-** it is desirable to avoid allocating a new page cache entry because
-** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
-** for all page cache needs and we should not need to spill the
-** allocation onto the heap.
-**
-** Or, the heap is used for all page cache memory but the heap is
-** under memory pressure, then again it is desirable to avoid
-** allocating a new page cache entry in order to avoid stressing
-** the heap even further.
-*/
-static int pcache1UnderMemoryPressure(PCache1 *pCache){
- if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
- return pcache1.bUnderPressure;
- }else{
- return sqlite3HeapNearlyFull();
- }
-}
-
-/******************************************************************************/
-/******** General Implementation Functions ************************************/
-
-/*
-** This function is used to resize the hash table used by the cache passed
-** as the first argument.
-**
-** The PCache mutex must be held when this function is called.
-*/
-static void pcache1ResizeHash(PCache1 *p){
- PgHdr1 **apNew;
- unsigned int nNew;
- unsigned int i;
-
- assert( sqlite3_mutex_held(p->pGroup->mutex) );
-
- nNew = p->nHash*2;
- if( nNew<256 ){
- nNew = 256;
- }
-
- pcache1LeaveMutex(p->pGroup);
- if( p->nHash ){ sqlite3BeginBenignMalloc(); }
- apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
- if( p->nHash ){ sqlite3EndBenignMalloc(); }
- pcache1EnterMutex(p->pGroup);
- if( apNew ){
- for(i=0; inHash; i++){
- PgHdr1 *pPage;
- PgHdr1 *pNext = p->apHash[i];
- while( (pPage = pNext)!=0 ){
- unsigned int h = pPage->iKey % nNew;
- pNext = pPage->pNext;
- pPage->pNext = apNew[h];
- apNew[h] = pPage;
- }
- }
- sqlite3_free(p->apHash);
- p->apHash = apNew;
- p->nHash = nNew;
- }
-}
-
-/*
-** This function is used internally to remove the page pPage from the
-** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
-** LRU list, then this function is a no-op.
-**
-** The PGroup mutex must be held when this function is called.
-*/
-static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
- assert( pPage!=0 );
- assert( PAGE_IS_UNPINNED(pPage) );
- assert( pPage->pLruNext );
- assert( pPage->pLruPrev );
- assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
- pPage->pLruPrev->pLruNext = pPage->pLruNext;
- pPage->pLruNext->pLruPrev = pPage->pLruPrev;
- pPage->pLruNext = 0;
- /* pPage->pLruPrev = 0;
- ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
- assert( pPage->isAnchor==0 );
- assert( pPage->pCache->pGroup->lru.isAnchor==1 );
- pPage->pCache->nRecyclable--;
- return pPage;
-}
-
-
-/*
-** Remove the page supplied as an argument from the hash table
-** (PCache1.apHash structure) that it is currently stored in.
-** Also free the page if freePage is true.
-**
-** The PGroup mutex must be held when this function is called.
-*/
-static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
- unsigned int h;
- PCache1 *pCache = pPage->pCache;
- PgHdr1 **pp;
-
- assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
- h = pPage->iKey % pCache->nHash;
- for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
- *pp = (*pp)->pNext;
-
- pCache->nPage--;
- if( freeFlag ) pcache1FreePage(pPage);
-}
-
-/*
-** If there are currently more than nMaxPage pages allocated, try
-** to recycle pages to reduce the number allocated to nMaxPage.
-*/
-static void pcache1EnforceMaxPage(PCache1 *pCache){
- PGroup *pGroup = pCache->pGroup;
- PgHdr1 *p;
- assert( sqlite3_mutex_held(pGroup->mutex) );
- while( pGroup->nPurgeable>pGroup->nMaxPage
- && (p=pGroup->lru.pLruPrev)->isAnchor==0
- ){
- assert( p->pCache->pGroup==pGroup );
- assert( PAGE_IS_UNPINNED(p) );
- pcache1PinPage(p);
- pcache1RemoveFromHash(p, 1);
- }
- if( pCache->nPage==0 && pCache->pBulk ){
- sqlite3_free(pCache->pBulk);
- pCache->pBulk = pCache->pFree = 0;
- }
-}
-
-/*
-** 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 */
- unsigned int iLimit /* Drop pages with this pgno or larger */
-){
- TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
- unsigned int h, iStop;
- assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
- assert( pCache->iMaxKey >= iLimit );
- assert( pCache->nHash > 0 );
- if( pCache->iMaxKey - iLimit < pCache->nHash ){
- /* If we are just shaving the last few pages off the end of the
- ** cache, then there is no point in scanning the entire hash table.
- ** Only scan those hash slots that might contain pages that need to
- ** be removed. */
- h = iLimit % pCache->nHash;
- iStop = pCache->iMaxKey % pCache->nHash;
- TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
- }else{
- /* This is the general case where many pages are being removed.
- ** It is necessary to scan the entire hash table */
- h = pCache->nHash/2;
- iStop = h - 1;
- }
- for(;;){
- PgHdr1 **pp;
- PgHdr1 *pPage;
- assert( hnHash );
- pp = &pCache->apHash[h];
- while( (pPage = *pp)!=0 ){
- if( pPage->iKey>=iLimit ){
- pCache->nPage--;
- *pp = pPage->pNext;
- if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
- pcache1FreePage(pPage);
- }else{
- pp = &pPage->pNext;
- TESTONLY( if( nPage>=0 ) nPage++; )
- }
- }
- if( h==iStop ) break;
- h = (h+1) % pCache->nHash;
- }
- assert( nPage<0 || pCache->nPage==(unsigned)nPage );
-}
-
-/******************************************************************************/
-/******** sqlite3_pcache Methods **********************************************/
-
-/*
-** Implementation of the sqlite3_pcache.xInit method.
-*/
-static int pcache1Init(void *NotUsed){
- UNUSED_PARAMETER(NotUsed);
- assert( pcache1.isInit==0 );
- memset(&pcache1, 0, sizeof(pcache1));
-
-
- /*
- ** The pcache1.separateCache variable is true if each PCache has its own
- ** private PGroup (mode-1). pcache1.separateCache is false if the single
- ** PGroup in pcache1.grp is used for all page caches (mode-2).
- **
- ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
- **
- ** * Use a unified cache in single-threaded applications that have
- ** configured a start-time buffer for use as page-cache memory using
- ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
- ** pBuf argument.
- **
- ** * Otherwise use separate caches (mode-1)
- */
-#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
- pcache1.separateCache = 0;
-#elif SQLITE_THREADSAFE
- pcache1.separateCache = sqlite3GlobalConfig.pPage==0
- || sqlite3GlobalConfig.bCoreMutex>0;
-#else
- pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
-#endif
-
-#if SQLITE_THREADSAFE
- if( sqlite3GlobalConfig.bCoreMutex ){
- pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
- pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
- }
-#endif
- if( pcache1.separateCache
- && sqlite3GlobalConfig.nPage!=0
- && sqlite3GlobalConfig.pPage==0
- ){
- pcache1.nInitPage = sqlite3GlobalConfig.nPage;
- }else{
- pcache1.nInitPage = 0;
- }
- pcache1.grp.mxPinned = 10;
- pcache1.isInit = 1;
- 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(void *NotUsed){
- UNUSED_PARAMETER(NotUsed);
- assert( pcache1.isInit!=0 );
- memset(&pcache1, 0, sizeof(pcache1));
-}
-
-/* forward declaration */
-static void pcache1Destroy(sqlite3_pcache *p);
-
-/*
-** Implementation of the sqlite3_pcache.xCreate method.
-**
-** Allocate a new cache.
-*/
-static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int 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 */
-
- assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
- assert( szExtra < 300 );
-
- sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
- pCache = (PCache1 *)sqlite3MallocZero(sz);
- if( pCache ){
- if( pcache1.separateCache ){
- pGroup = (PGroup*)&pCache[1];
- pGroup->mxPinned = 10;
- }else{
- pGroup = &pcache1.grp;
- }
- pcache1EnterMutex(pGroup);
- if( pGroup->lru.isAnchor==0 ){
- pGroup->lru.isAnchor = 1;
- pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
- }
- pCache->pGroup = pGroup;
- pCache->szPage = szPage;
- pCache->szExtra = szExtra;
- pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
- pCache->bPurgeable = (bPurgeable ? 1 : 0);
- pcache1ResizeHash(pCache);
- if( bPurgeable ){
- pCache->nMin = 10;
- pGroup->nMinPage += pCache->nMin;
- pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
- pCache->pnPurgeable = &pGroup->nPurgeable;
- }else{
- pCache->pnPurgeable = &pCache->nPurgeableDummy;
- }
- pcache1LeaveMutex(pGroup);
- if( pCache->nHash==0 ){
- pcache1Destroy((sqlite3_pcache*)pCache);
- pCache = 0;
- }
- }
- 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(pCache);
- pcache1LeaveMutex(pGroup);
- }
-}
-
-/*
-** Implementation of the sqlite3_pcache.xShrink method.
-**
-** Free up as much memory as possible.
-*/
-static void pcache1Shrink(sqlite3_pcache *p){
- PCache1 *pCache = (PCache1*)p;
- if( pCache->bPurgeable ){
- PGroup *pGroup = pCache->pGroup;
- int savedMaxPage;
- pcache1EnterMutex(pGroup);
- savedMaxPage = pGroup->nMaxPage;
- pGroup->nMaxPage = 0;
- pcache1EnforceMaxPage(pCache);
- pGroup->nMaxPage = savedMaxPage;
- 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 = pCache->nPage;
- pcache1LeaveMutex(pCache->pGroup);
- return n;
-}
-
-
-/*
-** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
-** in the header of the pcache1Fetch() procedure.
-**
-** This steps are broken out into a separate procedure because they are
-** usually not needed, and by avoiding the stack initialization required
-** for these steps, the main pcache1Fetch() procedure can run faster.
-*/
-static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
- PCache1 *pCache,
- unsigned int iKey,
- int createFlag
-){
- unsigned int nPinned;
- PGroup *pGroup = pCache->pGroup;
- PgHdr1 *pPage = 0;
-
- /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
- assert( pCache->nPage >= pCache->nRecyclable );
- nPinned = pCache->nPage - pCache->nRecyclable;
- assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
- assert( pCache->n90pct == pCache->nMax*9/10 );
- if( createFlag==1 && (
- nPinned>=pGroup->mxPinned
- || nPinned>=pCache->n90pct
- || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclablenPage>=pCache->nHash ) pcache1ResizeHash(pCache);
- assert( pCache->nHash>0 && pCache->apHash );
-
- /* Step 4. Try to recycle a page. */
- if( pCache->bPurgeable
- && !pGroup->lru.pLruPrev->isAnchor
- && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
- ){
- PCache1 *pOther;
- pPage = pGroup->lru.pLruPrev;
- assert( PAGE_IS_UNPINNED(pPage) );
- pcache1RemoveFromHash(pPage, 0);
- pcache1PinPage(pPage);
- pOther = pPage->pCache;
- if( pOther->szAlloc != pCache->szAlloc ){
- pcache1FreePage(pPage);
- pPage = 0;
- }else{
- pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
- }
- }
-
- /* Step 5. If a usable page buffer has still not been found,
- ** attempt to allocate a new one.
- */
- if( !pPage ){
- pPage = pcache1AllocPage(pCache, createFlag==1);
- }
-
- if( pPage ){
- unsigned int h = iKey % pCache->nHash;
- pCache->nPage++;
- pPage->iKey = iKey;
- pPage->pNext = pCache->apHash[h];
- pPage->pCache = pCache;
- pPage->pLruNext = 0;
- /* pPage->pLruPrev = 0;
- ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
- *(void **)pPage->page.pExtra = 0;
- pCache->apHash[h] = pPage;
- if( iKey>pCache->iMaxKey ){
- pCache->iMaxKey = iKey;
- }
- }
- return pPage;
-}
-
-/*
-** 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-purgeable 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.
-**
-** There are two versions of this routine. pcache1FetchWithMutex() is
-** the general case. pcache1FetchNoMutex() is a faster implementation for
-** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
-** invokes the appropriate routine.
-*/
-static PgHdr1 *pcache1FetchNoMutex(
- sqlite3_pcache *p,
- unsigned int iKey,
- int createFlag
-){
- PCache1 *pCache = (PCache1 *)p;
- PgHdr1 *pPage = 0;
-
- /* Step 1: Search the hash table for an existing entry. */
- pPage = pCache->apHash[iKey % pCache->nHash];
- while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
-
- /* Step 2: If the page was found in the hash table, then return it.
- ** If the page was not in the hash table and createFlag is 0, abort.
- ** Otherwise (page not in hash and createFlag!=0) continue with
- ** subsequent steps to try to create the page. */
- if( pPage ){
- if( PAGE_IS_UNPINNED(pPage) ){
- return pcache1PinPage(pPage);
- }else{
- return pPage;
- }
- }else if( createFlag ){
- /* Steps 3, 4, and 5 implemented by this subroutine */
- return pcache1FetchStage2(pCache, iKey, createFlag);
- }else{
- return 0;
- }
-}
-#if PCACHE1_MIGHT_USE_GROUP_MUTEX
-static PgHdr1 *pcache1FetchWithMutex(
- sqlite3_pcache *p,
- unsigned int iKey,
- int createFlag
-){
- PCache1 *pCache = (PCache1 *)p;
- PgHdr1 *pPage;
-
- pcache1EnterMutex(pCache->pGroup);
- pPage = pcache1FetchNoMutex(p, iKey, createFlag);
- assert( pPage==0 || pCache->iMaxKey>=iKey );
- pcache1LeaveMutex(pCache->pGroup);
- return pPage;
-}
-#endif
-static sqlite3_pcache_page *pcache1Fetch(
- sqlite3_pcache *p,
- unsigned int iKey,
- int createFlag
-){
-#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
- PCache1 *pCache = (PCache1 *)p;
-#endif
-
- assert( offsetof(PgHdr1,page)==0 );
- assert( pCache->bPurgeable || createFlag!=1 );
- assert( pCache->bPurgeable || pCache->nMin==0 );
- assert( pCache->bPurgeable==0 || pCache->nMin==10 );
- assert( pCache->nMin==0 || pCache->bPurgeable );
- assert( pCache->nHash>0 );
-#if PCACHE1_MIGHT_USE_GROUP_MUTEX
- if( pCache->pGroup->mutex ){
- return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
- }else
-#endif
- {
- return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
- }
-}
-
-
-/*
-** Implementation of the sqlite3_pcache.xUnpin method.
-**
-** Mark a page as unpinned (eligible for asynchronous recycling).
-*/
-static void pcache1Unpin(
- sqlite3_pcache *p,
- sqlite3_pcache_page *pPg,
- int reuseUnlikely
-){
- PCache1 *pCache = (PCache1 *)p;
- PgHdr1 *pPage = (PgHdr1 *)pPg;
- PGroup *pGroup = pCache->pGroup;
-
- 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.
- */
- assert( pPage->pLruNext==0 );
- assert( PAGE_IS_PINNED(pPage) );
-
- if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
- pcache1RemoveFromHash(pPage, 1);
- }else{
- /* Add the page to the PGroup LRU list. */
- PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
- pPage->pLruPrev = &pGroup->lru;
- (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
- *ppFirst = pPage;
- pCache->nRecyclable++;
- }
-
- pcache1LeaveMutex(pCache->pGroup);
-}
-
-/*
-** Implementation of the sqlite3_pcache.xRekey method.
-*/
-static void pcache1Rekey(
- sqlite3_pcache *p,
- sqlite3_pcache_page *pPg,
- unsigned int iOld,
- unsigned int iNew
-){
- PCache1 *pCache = (PCache1 *)p;
- PgHdr1 *pPage = (PgHdr1 *)pPg;
- PgHdr1 **pp;
- unsigned int h;
- assert( pPage->iKey==iOld );
- assert( pPage->pCache==pCache );
-
- pcache1EnterMutex(pCache->pGroup);
-
- h = iOld%pCache->nHash;
- pp = &pCache->apHash[h];
- while( (*pp)!=pPage ){
- pp = &(*pp)->pNext;
- }
- *pp = pPage->pNext;
-
- h = 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, unsigned int 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(sqlite3_pcache *p){
- PCache1 *pCache = (PCache1 *)p;
- PGroup *pGroup = pCache->pGroup;
- assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
- pcache1EnterMutex(pGroup);
- if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
- assert( pGroup->nMaxPage >= pCache->nMax );
- pGroup->nMaxPage -= pCache->nMax;
- assert( pGroup->nMinPage >= pCache->nMin );
- pGroup->nMinPage -= pCache->nMin;
- pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
- pcache1EnforceMaxPage(pCache);
- pcache1LeaveMutex(pGroup);
- sqlite3_free(pCache->pBulk);
- sqlite3_free(pCache->apHash);
- sqlite3_free(pCache);
-}
-
-/*
-** This function is called during initialization (sqlite3_initialize()) to
-** install the default pluggable cache module, assuming the user has not
-** already provided an alternative.
-*/
-SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
- static const sqlite3_pcache_methods2 defaultMethods = {
- 1, /* iVersion */
- 0, /* pArg */
- pcache1Init, /* xInit */
- pcache1Shutdown, /* xShutdown */
- pcache1Create, /* xCreate */
- pcache1Cachesize, /* xCachesize */
- pcache1Pagecount, /* xPagecount */
- pcache1Fetch, /* xFetch */
- pcache1Unpin, /* xUnpin */
- pcache1Rekey, /* xRekey */
- pcache1Truncate, /* xTruncate */
- pcache1Destroy, /* xDestroy */
- pcache1Shrink /* xShrink */
- };
- sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
-}
-
-/*
-** Return the size of the header on each page of this PCACHE implementation.
-*/
-SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
-
-/*
-** Return the global mutex used by this PCACHE implementation. The
-** sqlite3_status() routine needs access to this mutex.
-*/
-SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
- return pcache1.mutex;
-}
-
-#ifdef 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.
-*/
-SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
- int nFree = 0;
- assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
- assert( sqlite3_mutex_notheld(pcache1.mutex) );
- if( sqlite3GlobalConfig.pPage==0 ){
- PgHdr1 *p;
- pcache1EnterMutex(&pcache1.grp);
- while( (nReq<0 || nFreeisAnchor==0
- ){
- nFree += pcache1MemSize(p->page.pBuf);
-#ifdef SQLITE_PCACHE_SEPARATE_HEADER
- nFree += sqlite3MemSize(p);
-#endif
- assert( PAGE_IS_UNPINNED(p) );
- pcache1PinPage(p);
- pcache1RemoveFromHash(p, 1);
- }
- pcache1LeaveMutex(&pcache1.grp);
- }
- return nFree;
-}
-#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
-
-#ifdef SQLITE_TEST
-/*
-** This function is used by test procedures to inspect the internal state
-** of the global cache.
-*/
-SQLITE_PRIVATE void sqlite3PcacheStats(
- int *pnCurrent, /* OUT: Total number of pages cached */
- int *pnMax, /* OUT: Global maximum cache size */
- int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
- int *pnRecyclable /* OUT: Total number of pages available for recycling */
-){
- PgHdr1 *p;
- int nRecyclable = 0;
- for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
- assert( PAGE_IS_UNPINNED(p) );
- nRecyclable++;
- }
- *pnCurrent = pcache1.grp.nPurgeable;
- *pnMax = (int)pcache1.grp.nMaxPage;
- *pnMin = (int)pcache1.grp.nMinPage;
- *pnRecyclable = nRecyclable;
-}
-#endif
-
-/************** End of pcache1.c *********************************************/
-/************** Begin file rowset.c ******************************************/
-/*
-** 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. (Sometimes 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).
-**
-** TEST and SMALLEST may not be used by the same RowSet. This used to
-** be possible, but the feature was not used, so it was removed in order
-** to simplify the code.
-*/
-/* #include "sqliteInt.h" */
-
-
-/*
-** Target size for allocation chunks.
-*/
-#define ROWSET_ALLOCATION_SIZE 1024
-
-/*
-** The number of rowset entries per allocation chunk.
-*/
-#define ROWSET_ENTRY_PER_CHUNK \
- ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
-
-/*
-** Each entry in a RowSet is an instance of the following object.
-**
-** This same object is reused to store a linked list of trees of RowSetEntry
-** objects. In that alternative use, pRight points to the next entry
-** in the list, pLeft points to the tree, and v is unused. The
-** RowSet.pForest value points to the head of this forest list.
-*/
-struct RowSetEntry {
- i64 v; /* ROWID value for this entry */
- struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
- struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
-};
-
-/*
-** RowSetEntry objects 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.
-*/
-struct RowSetChunk {
- struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
- struct RowSetEntry aEntry[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.
-*/
-struct RowSet {
- struct RowSetChunk *pChunk; /* List of all chunk allocations */
- sqlite3 *db; /* The database connection */
- struct RowSetEntry *pEntry; /* List of entries using pRight */
- struct RowSetEntry *pLast; /* Last entry on the pEntry list */
- struct RowSetEntry *pFresh; /* Source of new entry objects */
- struct RowSetEntry *pForest; /* List of binary trees of entries */
- u16 nFresh; /* Number of objects on pFresh */
- u16 rsFlags; /* Various flags */
- int iBatch; /* Current insert batch */
-};
-
-/*
-** Allowed values for RowSet.rsFlags
-*/
-#define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
-#define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
-
-/*
-** Allocate a RowSet object. Return NULL if a memory allocation
-** error occurs.
-*/
-SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
- RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
- if( p ){
- int N = sqlite3DbMallocSize(db, p);
- p->pChunk = 0;
- p->db = db;
- p->pEntry = 0;
- p->pLast = 0;
- p->pForest = 0;
- p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
- p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
- p->rsFlags = ROWSET_SORTED;
- 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.
-*/
-SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
- RowSet *p = (RowSet*)pArg;
- struct RowSetChunk *pChunk, *pNextChunk;
- for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
- pNextChunk = pChunk->pNextChunk;
- sqlite3DbFree(p->db, pChunk);
- }
- p->pChunk = 0;
- p->nFresh = 0;
- p->pEntry = 0;
- p->pLast = 0;
- p->pForest = 0;
- p->rsFlags = ROWSET_SORTED;
-}
-
-/*
-** 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.
-*/
-SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
- sqlite3RowSetClear(pArg);
- sqlite3DbFree(((RowSet*)pArg)->db, pArg);
-}
-
-/*
-** Allocate a new RowSetEntry object that is associated with the
-** given RowSet. Return a pointer to the new and completely uninitialized
-** objected.
-**
-** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
-** routine returns NULL.
-*/
-static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
- assert( p!=0 );
- if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
- /* We could allocate a fresh RowSetEntry each time one is needed, but it
- ** is more efficient to pull a preallocated entry from the pool */
- struct RowSetChunk *pNew;
- pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
- if( pNew==0 ){
- return 0;
- }
- pNew->pNextChunk = p->pChunk;
- p->pChunk = pNew;
- p->pFresh = pNew->aEntry;
- p->nFresh = ROWSET_ENTRY_PER_CHUNK;
- }
- p->nFresh--;
- return p->pFresh++;
-}
-
-/*
-** Insert a new value into a RowSet.
-**
-** The mallocFailed flag of the database connection is set if a
-** memory allocation fails.
-*/
-SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
- struct RowSetEntry *pEntry; /* The new entry */
- struct RowSetEntry *pLast; /* The last prior entry */
-
- /* This routine is never called after sqlite3RowSetNext() */
- assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
-
- pEntry = rowSetEntryAlloc(p);
- if( pEntry==0 ) return;
- pEntry->v = rowid;
- pEntry->pRight = 0;
- pLast = p->pLast;
- if( pLast ){
- if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
- /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
- ** where possible */
- p->rsFlags &= ~ROWSET_SORTED;
- }
- pLast->pRight = pEntry;
- }else{
- 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 struct RowSetEntry *rowSetEntryMerge(
- struct RowSetEntry *pA, /* First sorted list to be merged */
- struct RowSetEntry *pB /* Second sorted list to be merged */
-){
- struct RowSetEntry head;
- struct RowSetEntry *pTail;
-
- pTail = &head;
- assert( pA!=0 && pB!=0 );
- for(;;){
- assert( pA->pRight==0 || pA->v<=pA->pRight->v );
- assert( pB->pRight==0 || pB->v<=pB->pRight->v );
- if( pA->v<=pB->v ){
- if( pA->v